translate() CSS Function
Description
The CSS translate()
function repositions an element in the horizontal and/or vertical directions. It is a member of the transform
property, which allows you to rotate, scale, skew, or translate an element.
The translate()
function takes one or two arguments:
- The first argument is the horizontal translation distance. This can be specified in pixels, percentages, or other CSS units. A positive value moves the element to the right, while a negative value moves the element to the left.
- The second argument is the vertical translation distance. This is optional, and if omitted, the vertical translation will be set to zero. A positive value moves the element down, while a negative value moves the element up.
For example, the following CSS will translate an element 100 pixels to the right and 50 pixels down:
transform: translate(100px, 50px);
The translate()
function can be used to create a variety of effects, such as:
- Centering an element on the page
- Creating a sliding navigation menu
- Animating elements on hover
Here is an example of how to use the translate()
function to center an element on the page:
.centered-element {
transform: translate(-50%, -50%);
}
The -50%
values in the translate()
function tell the browser to move the element half of its width and half of its height to the left and up, respectively. This will effectively center the element on the page.
Syntax
transform: translate( tx [, ty ]? ); /* the question mark indicates the second value is optional */
Values
- txHorizontal shift. A positive value shifts to the right, a negative value to the left.
- tyVertical shift. A positive value moves up, a negative value down. If the value is not specified, then the default value is 0 and no vertical shift occurs.
Example
<img class="translate" src="images/nature.jpg" alt="Nature Image">
.translate {
transform: translate(50px, 30px);
}
Browser Support
The following table will show you the current browser support for the CSS translate()
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