CSS translate() Function – How to Reposition Elements in CSS
translate() transforms an element by repositioning (translating) it two-dimensionally.
Syntax of the CSS translate()
Function
translate()
accepts two arguments. Here is the syntax:
element {
transform: translate(x, y);
}
Note the following:
- The
x
argument can be a length or percentage value. It specifies the distance you wish to move the element from its original x-axis position. - The
y
argument can be a length or percentage value. It specifies the distance you wish to move the element from its original y-axis position. y
is an optional argument.
Examples of the CSS translate()
Function
Below are some examples of how the CSS translate()
function works.
How to translate an element along only the X-axis
- CSS
- HTML
img {
transform: translate(150px);
width: 80%;
}
<img
src="https://cdn.pixabay.com/photo/2022/09/26/23/26/african-american-7481724_960_720.jpg"
alt=""
/>
The snippet above used the translate()
function to reposition the image 150px
away from its original position along the x-axis.
translate(150px)
is equivalent to translateX(150px)
.
How to translate an element along only the Y-axis
- CSS
- HTML
img {
transform: translate(0, 55%);
width: 80%;
}
<img
src="https://cdn.pixabay.com/photo/2022/09/26/23/26/african-american-7481724_960_720.jpg"
alt=""
/>
The snippet above used the translate()
function to reposition the image 55%
away from its original position along the y-axis.
- A zero (
0
) translate distance tells browsers not to apply any translating effect on the selected element. translate(0, 55%)
is equivalent totranslateY(55%)
.
How to translate an element along the X- and Y-axis
- CSS
- HTML
img {
transform: translate(60%, 300px);
width: 80%;
}
<img
src="https://cdn.pixabay.com/photo/2022/09/26/23/26/african-american-7481724_960_720.jpg"
alt=""
/>
The snippet above used the translate()
function to reposition the image 60%
away from its original position along the x-axis. And 300px
from its y-axis.
Overview
This article discussed what a CSS translate()
function is. We also used examples to see how it works.