translateX() CSS Function
Description
The CSS translateX()
function is used to move an element horizontally along the x-axis. It takes a single parameter, which is the distance to move the element. The distance can be specified in pixels, centimeters, inches, or percentages.
For example, the following CSS code would move the element with the id my-element
100 pixels to the right:
#my-element {
transform: translateX(100px);
}
The translateX()
function can be used to create a variety of effects, such as sliding menus, animating images, and creating responsive layouts. It can also be used in conjunction with other CSS transform functions, such as translateY()
and rotate()
, to create more complex animations.
Here are some examples of how the translateX()
function can be used:
- Create a sliding menu: You can use the
translateX()
function to create a sliding menu that can be opened and closed by clicking on a button. For example, the following CSS code would create a sliding menu that is hidden by default and slides in from the left when the user clicks on the button with the idopen-menu
:
#menu {
position: fixed;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background-color: white;
transform: translateX(-100%);
transition: transform 0.5s ease-in-out;
}
#open-menu {
position: fixed;
top: 0;
left: 0;
width: 50px;
height: 50px;
background-color: blue;
}
#open-menu:hover {
cursor: pointer;
}
#open-menu:click {
#menu {
transform: translateX(0);
}
}
- Animate images: You can use the
translateX()
function to animate images. For example, the following CSS code would make the image with the idmy-image
slide from the left to the right over a period of 2 seconds:
#my-image {
transform: translateX(-100%);
transition: transform 2s ease-in-out;
}
#my-image.animate {
transform: translateX(0);
}
- Create responsive layouts: You can use the
translateX()
function to create responsive layouts that adapt to different screen sizes. For example, the following CSS code would center the element with the idmy-element
on the screen, regardless of the screen size:
#my-element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Syntax
transform: translate(tx);
Values
- txHorizontal shift. A positive value shifts to the right, a negative value to the left.
Example
<img class="translate" src="images/nature.jpg" alt="Nature Image">
.translate {
transform: translateX(80px);
}
Browser Support
The following table will show you the current browser support for the CSS translateX()
function.
Desktop | |||||
![]() |
![]() |
![]() |
![]() |
![]() |
|
12 | 1 | 3.5 | 10.5 | 3.1 |
Tablets / Mobile | |||||
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
18 | 4 | 11 | 3.2 | 1 | 2 |
Last updated by CSSPortal on: 7th October 2023