CSS Units

CSS Units

Subscribe to my newsletter and never miss my upcoming articles

Hello Fellow Codenewbies 👋

There are many factors in CSS to be considered when we think about responsiveness.
One of them is CSS Units.


There are two types of units:

  1. Absolute
  2. Relative - to the size of font (em, rem, etc.) and viewport (vh, vw, etc.)


  • Absolute Unit

    Regardless of its parent's or screen size, absolute units are always be the same size.
    px, cm, inch, etc. are within this category.
<body>
  <div class="absolute"></div>
  <div class="relative"></div>
</body>
.absolute {
  background-color: green;
  width: 640px;
  height: 100px;
}

.relative {
  background-color: red;
  width: 90%;
  height: 6em;
}

Try to shrink and expand the window in this example and see the difference.

  • Percentage

    Percentage mainly use for widths and it is relative to the target element's parent.
<body>
  <header>
    <h1>Hello World</h1>
  </header>
</body>
header {
  width: 80%;
}

h1 {
  width: 50%;
}

Width of header is 80% of body and h1 is 50% of header.

  • em

    em inherits size from its parent.
<div class="container">
  <h1>Hello World</h1>
</div>
.container {
  font-size: 12px;
}

h1 {
  font-size: 2em;
}

The font size of h1is 2x of its parent (container), which makes it 24px.

But there is one problem with em. Because it is relative to its parent, it can create a cascading effect.

<body>
  <div class="container">
    <h1>Hello World</h1>
    <ul>
      <li>List 1</li>
      <li>List 2</li>
      <li>List 3</li>
    </ul>
  </div>
</body>
body {
  font-size: 18px;
}

h1 {
  font-size: 2em;
}

ul {
  font-size: 1.5em;
}

li {
  font-size: 1.5em;  
}

I provide the example in Codepen here.
In this example, all font size of li are bigger than h1.
This happens because the font size of li is 1.5x bigger than ul, while ul is 1.5x bigger than body, which makes li font size 3x bigger than body's font size.
While h1 font size is set as 2x bigger than body.

So when it's about font-size, we better avoid the using of em and use rem instead.

  • rem

    rem stands for "root element" and it is always relative to the "root" of the document, which is html element.
<body>
  <div class="container">
    <h1>Hello World</h1>
    <ul>
      <li>List 1</li>
      <li>List 2</li>
      <li>List 3</li>
    </ul>
  </div>
</body>
html {
  font-size: 10px;
}

body {
  font-size: 18px;
}

h1 {
  font-size: 2rem;
}

ul {
  font-size: 1.5rem;
}

li {
  font-size: 1.5rem;  
}

You can see the code in action here.
Regardless that the body has 18px of font size, all rem are relative to html as the root element.

Picking Which Unit To Use

It really depends on your personal preference and what you need, but here is a reference of approaches on when to use one:

  • font-size: rem

  • margin and padding: em

  • width: em or percentage or absolute unit such as px

 
Share this