CSS transformations tutorial with examples

I was desperately trying to achieve the effect of vertical text using CSS transformations but my page didn't look as I wanted. I was actually missing something, so I decided to run a couple of tests using the CSS3 transform property which is currently supported only through vendor prefixes. The first thing we need to understand is that a transformation (e.g. a rotation) applies to the whole box is attached to. So it's not the text that is rotating, but the whole containing block of the element.

For that reason, text seems to shift to left, right, top and bottom depending on the number of degrees we've specified in our CSS. But remember: it's not the text that's rotating, but the box where the text is contained. Let's start with a normal state, that is, a box with a child element that is not transformed:

div.test {
 width: 100%;
 height: 300px;
 margin-bottom: 1em;
 position: relative;
 background: silver;

div.test div {
 width: 150px;
 height: 150px;
 position: absolute;
 top: 50%;
 left: 50%;
 margin: -75px 0 0 -75px;

div.normal {
 background: #eee;
 font-size: 1.5em;

View the example

As you can see, the text within the element is normally placed in the top left corner of the box. Now let's try to apply a rotation of 90 degrees:

#test1 {
 background: yellow;
 -moz-transform: rotate(90deg);
 -webkit-transform: rotate(90deg);
 -o-transform: rotate(90deg);
 transform: rotate(90deg);
 font-size: 1.5em;

View the example

See what's happened? Text moved to the right, but it's only apparent: in fact, it's the box that did rotate by 90 degrees clockwise. Now let's try the opposite situation: a rotation of minus 90 degrees:

#test2 {
 background: orange;
 font-size: 1.5em;
 -moz-transform: rotate(-90deg);
 -webkit-transform: rotate(-90deg);
 -o-transform: rotate(-90deg);
 transform: rotate(-90deg);

View the example

Now the box position along its axis has changed by minus 90 degrees counterclockwise and the text position has changed too so that it appears on the left bottom corner. Finally, let's try two minor changes: a rotation by 10 degrees and another one by minus 10 degrees:

#test3 {
 background: teal;
 font-size: 1.5em;
 -moz-transform: rotate(10deg);
 -webkit-transform: rotate(10deg);
 -o-transform: rotate(10deg);
 transform: rotate(10deg);

View the example

#test4 {
 background: red;
 font-size: 1.5em;
 -moz-transform: rotate(-10deg);
 -webkit-transform: rotate(-10deg);
 -o-transform: rotate(-10deg);
 transform: rotate(-10deg);

View the example

Now text appears only a little bit slanted, but it's actually the rotation of its box that makes this possible. You can see all these tests below.


Live tests

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.