Transforms

CSS transforms allow us to apply rotation, skewing, and scaling transformations to an HTML element in both the 2D plane and in 3D space.

The two main transform properties that we’ll use are transform-origin and transform.

The transform-origin property allows us to move the origin of the element which is used by various transforms.  For example we can rotate an element about the x-axis that runs through the origin.   By default the origin is set to the center of the element.

The transform property specifies one or more transforms to apply to the element.  The transforms that we can perform on elements are:

  • translate (move horizontally and vertically)
  • scale (make an element larger or smaller)
  • rotate (rotate the element about the x, y or z axis)
  • skew (deform the element)

See the transform documentation for details.

Example 1

In the example below, we rotate the button about the Y axis when the mouse hovers over the element. We do this in conjunction with the transition property so that the state change occurs over a 2 second interval.  Notice that the button returns to its original state (via a reverse rotations) when the mouse navigates off of the button.

 <div id="purpleButton" class="button"></div>
.button { 
    display: inline-block; 
    padding: 20px; 
    border-radius: 20px; 
}
#purpleButton {
    background-color: purple; 
    transition: all 2s;
}
#purpleButton:hover {
    transform: rotateY(360deg);
}

Example 2

In this example we translate a button along the x-axis.

 <div id="yellowButton" class="button"></div>
.yellow { 
    display: inline-block; 
    padding: 20px; 
    border-radius: 20px; 
}
#yellowButton {
    background-color: yellowgreen; 
    transition: all 2s;
}
#yellowButton:hover {
    transform: translatex(400px);
}

© 2018 – 2021, Eric. All rights reserved.