How to Use Rotate in CSS: Simple Guide with Examples
Use the CSS
transform property with the rotate(angle) function to rotate an element by a specified angle. For example, transform: rotate(45deg); rotates the element 45 degrees clockwise.Syntax
The rotate() function is used inside the transform property to rotate an element. The angle can be specified in degrees (deg), radians (rad), turns (turn), or gradians (grad).
- transform: CSS property to apply transformations.
- rotate(angle): rotates the element by the given angle.
css
selector {
transform: rotate(45deg);
}Example
This example shows a square div rotated 45 degrees clockwise using transform: rotate(45deg);. The rotation happens around the element's center by default.
html
<!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: #4CAF50; transform: rotate(45deg); margin: 50px; } </style> </head> <body> <div class="box"></div> </body> </html>
Output
A green square rotated diagonally (45 degrees) on a white background.
Common Pitfalls
Common mistakes when using rotate() include:
- Forgetting to use the
transformproperty and writingrotate()alone. - Not specifying units for the angle (e.g., writing
rotate(45)instead ofrotate(45deg)). - Unexpected rotation origin causing the element to rotate around a corner instead of the center.
To fix the rotation origin, use transform-origin property.
css
/* Wrong: missing transform property */ .box { rotate(45deg); } /* Correct: use transform with rotate */ .box { transform: rotate(45deg); } /* Fix rotation origin to top left */ .box { transform: rotate(45deg); transform-origin: top left; }
Quick Reference
| Property | Description | Example |
|---|---|---|
| transform | Applies transformation functions like rotate | transform: rotate(30deg); |
| rotate(angle) | Rotates element by angle (deg, rad, turn, grad) | rotate(90deg) |
| transform-origin | Sets the pivot point for rotation | transform-origin: center; |
| deg | Degrees unit for angles | 45deg |
| turn | Turns unit (1 turn = 360 degrees) | 0.5turn |
Key Takeaways
Use the transform property with rotate(angle) to rotate elements in CSS.
Always specify the angle unit like deg, rad, or turn when using rotate.
The rotation happens around the element's center by default but can be changed with transform-origin.
Forgetting transform or units are common mistakes to avoid.
Rotate can be combined with other transform functions for complex effects.