Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Transform the element along with x-axis and y-axis with CSS
The CSS translate() function is used to move an element from its current position along the x-axis and y-axis. This transformation does not affect the document flow, meaning other elements remain in their original positions.
Syntax
transform: translate(x, y);
Where:
-
x− a length value representing the horizontal displacement -
y− a length value representing the vertical displacement (optional, defaults to 0)
Example: Moving Element Along Both Axes
The following example demonstrates how to translate an element 30px to the right and 20px down −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
position: relative;
width: 300px;
height: 200px;
border: 2px solid #ccc;
margin: 20px;
}
.box {
width: 50px;
height: 50px;
background-color: orange;
margin: 10px;
display: inline-block;
}
.translated {
transform: translate(30px, 20px);
background-color: #4CAF50;
}
</style>
</head>
<body>
<div class="container">
<div class="box">Original</div>
<div class="box translated">Translated</div>
</div>
</body>
</html>
Two boxes appear: an orange box in its original position, and a green box moved 30px right and 20px down from where it would normally be positioned.
Example: Single Value Translation
When only one value is provided, it applies to the x-axis only −
<!DOCTYPE html>
<html>
<head>
<style>
.box {
width: 80px;
height: 50px;
background-color: #ff6b6b;
margin: 20px;
color: white;
text-align: center;
line-height: 50px;
}
.move-right {
transform: translate(50px);
}
</style>
</head>
<body>
<div class="box">Original</div>
<div class="box move-right">Moved</div>
</body>
</html>
Two red boxes with white text: the first in its normal position, and the second moved 50px to the right only.
Conclusion
The translate() function provides an efficient way to move elements without affecting the document layout. Use two values to move along both axes, or a single value for horizontal-only movement.
Advertisements
