How to Use Translate in CSS: Simple Guide with Examples
Use the
translate() function inside the transform property in CSS to move an element horizontally and/or vertically. For example, transform: translate(50px, 100px); moves the element 50 pixels right and 100 pixels down.Syntax
The translate() function is used with the transform property to move elements in 2D space. It takes two values: the first moves the element horizontally (X-axis), and the second moves it vertically (Y-axis). You can use length units like px, em, or percentages.
Example parts:
transform:CSS property to apply transformations.translate(x, y): moves element byxhorizontally andyvertically.
css
transform: translate(50px, 100px);
Example
This example moves a blue box 100 pixels right and 50 pixels down using translate(). The box stays in the document flow but visually shifts position.
css
html, body {
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background-color: #f0f0f0;
}
.box {
width: 100px;
height: 100px;
background-color: #007bff;
transform: translate(100px, 50px);
transition: transform 0.3s ease;
}
Output
A blue square box appears shifted 100 pixels to the right and 50 pixels down from the center of the page on a light gray background.
Common Pitfalls
Common mistakes when using translate() include:
- Forgetting to use
transformproperty and writingtranslate()alone. - Using only one value, which moves horizontally but leaves vertical as zero.
- Using units incorrectly or mixing units (e.g.,
translate(50, 100px)is invalid). - Expecting
translate()to affect document flow (it only moves visually).
css
/* Wrong: translate alone does nothing */ .element { /* translate(50px, 50px); is invalid CSS */ } /* Correct: use transform property */ .element { transform: translate(50px, 50px); }
Quick Reference
| Property | Description | Example |
|---|---|---|
| transform | Applies transformation functions like translate | transform: translate(20px, 30px); |
| translate(x, y) | Moves element by x horizontally and y vertically | translate(50px, 100px) |
| translateX(x) | Moves element only horizontally | translateX(40px) |
| translateY(y) | Moves element only vertically | translateY(60px) |
| Units | Use length units like px, em, %, etc. | translate(10%, 5em) |
Key Takeaways
Use the transform property with translate(x, y) to move elements in 2D space.
Translate moves elements visually without changing their layout position.
Always specify units for translate values, like px or %, for correct behavior.
Use translateX() or translateY() for moving in only one direction.
Remember translate() requires the transform property to work.