Explain Codes LogoExplain Codes Logo

How to rotate a <div> 90 degrees?

html
css
transform
hover
Anton ShumikhinbyAnton Shumikhin·Aug 19, 2024
TLDR

Quickly rotate a <div> by utilizing CSS's transform: rotate(90deg);:

<div style="transform: rotate(90deg);">Rotated 90°</div>

What you've got here is a 90° clockwise rotation using just one line of code.

To add a smooth transition effect during rotation, use:

div { transition: transform 0.5s ease-in-out; /* Smooth operator */ }

This code results in visually appealing gradual rotation for your div.

Step-by-step guide

Using CSS transform

The principal method for rotation is the transform: rotate(90deg); function. Here's how to rotate a <div> without requiring any user interactions like :hover:

#rotate-me { transform: rotate(90deg); /* Around the world */ }

Adjusting styles post-rotation

Rotate and then adjust style properties such as width, height, and borders accordingly:

#make-over { width: 100px; height: 200px; border: 1px solid black; transform-origin: top left; /* I dare you to move */ }

Appreciating the ‘transform’ property

The CSS transform attribute also provides other effects like scaling, translating, and skewing. For example:

#do-the-wave { transform: skew(20deg) scale(1.2); /* Twisting by the pool! */ }

Rotating on hover

Adding a hover effect with :hover pseudo-class that triggers rotation:

#hovercraft { transform: rotate(90deg); transition: transform 0.5s; /* Transitions, the hovercrafts of CSS */ }

Vendor prefixes in retrospect

Earlier, to ensure cross-browser compatibility, vendor prefixes like -webkit- or -ms- were required. However, the standardized transform syntax is now well-adopted across most modern browsers. However, don't forget to consider any edge cases!

Experience enhances proficiency

Combine transformations for complex effects

For complex transformations, transform allows combinations of rotation, scaling, and other effects:

div { transform: rotate(90deg) scale(1.5); // TRANSFORMERS, DIVs in disguise! }

Fixing styling issues post-rotation

Remember that post-rotation, elements might overlap or offset due to changes in their dimensional properties. Use the position property to resolve these.

Accessibility over aesthetics

Although animations can add zest to your site, ensure they don't hinder the experience for users with screen readers or individuals with motion sensitivity. Balance is key.