CSS 2D Transforms
The CSS transform property allows you to move, rotate, scale, and skew elements. These transformations happen in 2D space and do not affect the layout of surrounding elements because they are applied after the element is rendered.
transform Property
The transform property can accept one or more transform functions as its value.
translate()
The translate() function moves an element horizontally and/or vertically. It accepts one or two values.
translate(x, y): Moves along the X-axis and Y-axis respectively.translate(x): Moves only along the X-axis.translateX(x): Same as above.translateY(y): Moves only along the Y-axis.
div {
transform: translate(50px, 100px);
}rotate()
The rotate() function rotates an element clockwise. It accepts an angle value.
- Units:
deg(degrees),grad(gradians),rad(radians),turn(turns). The most commonly used isdeg.
div {
transform: rotate(20deg);
}scale()
The scale() function resizes an element.
scale(x, y): Scales along the X-axis and Y-axis respectively. Values > 1 increase the size, values < 1 decrease the size.scale(number): Scales proportionally along both X and Y axes.scaleX(x): Scales only along the X-axis.scaleY(y): Scales only along the Y-axis.
div {
transform: scale(2, 0.5); /* Width doubles, height halves */
}skew()
The skew() function skews an element along the X and Y axes. It accepts one or two angle values.
skew(x-angle, y-angle)skewX(angle): Skews only along the X-axis.skewY(angle): Skews only along the Y-axis.
div {
transform: skewX(20deg);
}transform-origin Property
By default, all transformations occur around the center point of the element (50% 50%). The transform-origin property allows you to change this origin of transformation.
div {
transform: rotate(45deg);
transform-origin: 20% 40%;
}Multiple Transforms
You can apply multiple transform functions in a single transform declaration, separated by spaces. Note that the order of application matters, as subsequent transforms are based on the result of the previous ones.
div {
transform: translate(50px) rotate(30deg) scale(1.2);
}2D transforms are especially powerful when combined with transition and animation properties to create smooth, eye-catching dynamic effects.