CSS rotate property
The rotate
property in CSS is used to rotate an element around a fixed point, typically its center, by a specified angle. This transformation can be used to create visual effects such as spinning or tilting elements, and it can be applied in both 2D and 3D space.
Syntax
transform: rotate(angle);
angle
: This is the degree of rotation. It can be specified in various units:- Degrees (
deg
): The most common unit, where360deg
equals a full circle,180deg
equals half a circle, etc. - Radians (
rad
): Where2π rad
equals a full circle. - Gradians (
grad
): Where400grad
equals a full circle. - Turns (
turn
): Where1turn
equals a full circle.
- Degrees (
Example: Rotating an Element by 45 Degrees
.box {
width: 100px;
height: 100px;
background-color: lightblue;
transform: rotate(45deg);
}
- This code rotates the
.box
element 45 degrees clockwise around its center.
Rotating in the Opposite Direction
To rotate an element counterclockwise, you can use a negative angle:
.box {
transform: rotate(-45deg);
}
- This rotates the element 45 degrees counterclockwise.
Combining rotate
with Other Transform Functions
The rotate
function can be combined with other transform functions like translate
, scale
, or skew
. Multiple transformations can be applied in sequence:
.box {
transform: translateX(50px) rotate(45deg);
}
- This moves the element 50 pixels to the right and then rotates it 45 degrees.
Rotating Around a Different Origin
By default, the rotation occurs around the element's center, but you can change the rotation point using the transform-origin
property:
.box {
transform-origin: top left;
transform: rotate(45deg);
}
- In this case, the element rotates 45 degrees around its top-left corner.
3D Rotation
You can also rotate an element in 3D space using rotateX
, rotateY
, and rotateZ
:
rotateX(angle)
: Rotates the element around the X-axis.rotateY(angle)
: Rotates the element around the Y-axis.rotateZ(angle)
: Rotates the element around the Z-axis (equivalent torotate
in 2D).
.box {
transform: rotateX(45deg) rotateY(30deg);
}
- This rotates the element 45 degrees around the X-axis and 30 degrees around the Y-axis, creating a 3D effect.
Practical Example
HTML and CSS Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rotate Example</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: lightblue;
margin: 50px;
transition: transform 0.5s ease;
}
.box:hover {
transform: rotate(90deg);
}
</style>
</head>
<body>
<div class="box">Hover me!</div>
</body>
</html>
Explanation
- Initial State: The
.box
element is a square with a light blue background. - On Hover: When you hover over the box, it rotates 90 degrees clockwise, making it appear as if it turns on its axis.