CSS Units

Selecting the perfect unit for your CSS code can be daunting. Here, is a basic explanation of the most used units and which ones to go for your styling needs.

Units are broadly classified into two categories:-

  1. Absolute units
  2. Relative units

Confused about what they are? Read on...

Absolute units are fixed. They do not change to adjust with changing screen size. For eg., A person could view a website from his desktop browser or in his free time, from his phone.

px (pixel) is the most commonly used absolute unit.

While on the one hand, they give a clear idea to the developer as to how the website will look but they fail when it comes to adjusting to different screen sizes.

Here is where relative units come into the picture.

Relative units, as the name suggests, are dependent on some other entity, for eg. font size.

A few examples of Relative units are:-

  1. rem
  2. em
  3. %
  4. vw
  5. vh etc.

The most commonly used ones are:- rem & em.

1. rem

To use this unit, one can define the font-size of the root element at the top of the CSS file. This can be done using any absolute unit. Post this, anywhere a varying size followed by rem can be used.

For example:-

html{
  font-size: 16px;
}

p{
  font-size: 2rem;
}

The above code snippet will result in the paragraph font-size to be 32px.

2. em

This is a local unit. Using em results in a multiple of the font-size mentioned to that block of code.

For example:-

p {
  font-size: 16px;
  line-height: 0.8em;
}

The line-height of the paragraph here will be 0.8 times 16px.

3. %

The % unit is also a global unit. It acts relative to its parent. The font-size defined for the root element at the top acts as the parent for this unit. For example:-

body {
 font-size:20px;
}

p {
  font-size: 130%;
}

Here, the font-size of the paragraph will be 130% of 20px.

That is it for today. See you in the next one!