CSS Scaling

Chapter 40 4 mins

Learning outcomes:

  1. What is scaling
  2. Using the scale() function

What is scaling?

In transformations, scaling is to resize an element in the horizontal and/or vertical proportions. The scale factor k determines the degree of scaling.

If less than 1 it scales down the element; if more than 1 it scales up an element; if equal to 1 the element remains in it's original scale.

The scale(k) function allows us to scale objects around an HTML document with a scale factor, k, which is just a number.

Scaling up or down

Take a look at the following example showing two different elements, one in its original proportions and one scaled up i.e enlarged using scale(1.5).

Scale me
Scale me

The scaled element is 2.25 times greater than the area of the original element.

An understanding of the scale factor, k.

Each dimension of an element is multiplied by the scale factor, k to get the corresponding scaled dimension. For instance if an element measures 20px by 20px then its scaled width for k = 2 will be 20 x 2 = 40px. The height will also be of this value and hence the the element will become four times as bigger as before - not two times!

Instead of just one side being scaled up or down, we have it scaling being applied on both the sides and therefore whatever the factor k is our final area is square of the k factor.

Just a touch of math, that's it.

To scale an element in one direction only use the respective funtions scaleX() or scaleY() or the same scale() function with specifying two parameters of which one is zero.

Seperate sides - seperate scaling

In CSS, we can use the functions scaleX() and scaleY() to scale up or down the width and the height of an element respectively and seperately.

Both functions play with their respective dimensions only and therefore sometimes can even disproportionate an element out of its original dimensions ratio.

Let's see each function in action.

scaleX() - width scaling

scaleX(k) serves to scale the width of an element by a factor k. Following we double the width of div element:

Initial style:

Scale me
div {
    transform: scaleX(2); /* scaled width = width x 2 */
}
Scale me
In scaling the width of the div here, to double of its original size, we also get the text within it scaled. This is because scaling simply scales everything!

scaleY() - height scaling

Similar to scaleX(), scaleY(k) serves to scale the height of an element by a factor of k.

Following we double the height of the div using k as 2:

div {
    transform: scaleY(2); /* scaled height = height x 2 */
}
Scale me

And this is it for CSS transformations in terms of scaling.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage