DEV Community

Cover image for 5 CSS units and their recommended use-case
Habdul Hazeez
Habdul Hazeez

Posted on

5 CSS units and their recommended use-case

Cover photo by Zan on Unsplash.

Introduction

CSS has units that surely cannot be covered in one article, a documentation or some sort will be befitting for that.

In this article we'll cover the CSS units that you'll regularly come across and recommendation on when it's best to use them.

The units we'll talk about are:

  • The em unit
  • Root em written as rem.
  • Pixels written as px.
  • Percentage written as %.
  • Viewport width written as vw.

Let's begin.


The em unit

The em unit is a relative unit meaning it describes a length relative to another length property.

In typography, one em is equal to 16 points and this value is the default font size in most modern browser unless it's changed by the user.

Default font size in Firefox Web browser
Default font size in Firefox

Recommended use-case

This unit scales and it's best used in the following situations:

Further reading

Root em

The root em is calculated relative to the root em. The root em is usually the browser default font size.

The root element on a Web page is usually the html tag or the ::root pseudo-element.

Have a look at the following code snippet.

/**
 * The computed font size value assume the
 * browser defualt font size is 16px.
 */
p {
    font-size: 3rem; /* 48px computed by the browser */
}
Enter fullscreen mode Exit fullscreen mode

Recommended use-case

  • Font sizing that does not need em units as demonstrated in the preceding code snippet.

Further reading

Pixel unit

Bert Bos describes the px unit as the magic unit of CSS. (source).

Whether you use rem, em or other units the computed browser equivalent will be in px.

Recommended use-case

  • Sizing of border width

Further reading

Percentage unit

The percentage unit is a relative unit and it's written as %. It is used to define a size relative to the parents object.

Have a look at the following example.

.container {
    width: 50%; /* Half of its parent width */
}
Enter fullscreen mode Exit fullscreen mode

Recommended use-case

  • Responsive web design

Further reading

Viewport width unit

The viewport unit is used to dictate the width of the current viewport that an element can occupy.

It's written in vw and it has a close relative called the viewport height (vh).

Recommended use-case

  • Any sizing that requires changes with the viewport's width.

Further reading

Conclusion

These are the units you'll use most of the time but I'll encourage you to experiment further with them and other units not discussed here.

You can check Mozilla Developer Network Values and units article.

Top comments (0)