How to Rotate Text 90 degrees in CSS?

Rotation in CSS is mostly performed using the transform property. This property supports several rotation methods such as rotateX(), rotateY(), rotate(), rotate3d(), etc. which allows you to rotate any HTML element.

In this article, we are going to learn how we can rotate text 90 degrees on the XY plane(2D space). To do this we will use the rotate() function.

The rotate() function allows you to rotate any HTML element in a 2-dimensional space. The value of the rotation angle can be specified in degrees. for e.g. rotate(90deg)

A positive value of the rotation angle rotates the element in the clockwise direction while a negative value rotates the element in the anti-clockwise direction.

Here is an example which rotates an <h2> element 90 degrees in clockwise direction:

Example:

h2{
   display: inline-block;
   transform: rotate(90deg);
   transform-origin: left;
   background-color: yellow;
   margin-left: 30px;
}

Similarly, if you want to rotate the text -90 degrees, you can use rotate(-90deg).

But, if you directly specify rotate(-90deg), some of the text might be clipped off. This is because the element rotates around its center by default. Therefore, the top half of the element might overflow if the parent container does not have enough height.

To avoid this problem we have to rotate the element -90 degrees around its top right corner. Which we can easily do by specifying the transform-origin to top right.

Here is an example which rotates the <h2> element -90 degrees:

Example:

h2{
   display: inline-block;
   transform: rotate(-90deg);
   transform-origin: top right;
   background-color: yellow;
   margin-left: 30px;
}

We can also fix the above problem without additionally setting the transform-origin to top right.

The basic idea is to pull the top half of the element(which is overflowing) back to its original position. This we can easily do by translating the element -50% on the X-axis.

See this example:

Example:

h2{
   display: inline-block;
   transform: rotate(-90deg) translateX(-50%);
   background-color: yellow;
   margin-left: 30px;
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.