A Beginner’s Guide to CSS Sizing Units

CSS sizing units determine how elements like text, images, margins, padding, and containers are measured and displayed on a web page.

1. Numbers

Numbers are integers (1, 2, 3) and decimals (.1, .2, .3). Numbers are used to define opacity and line-height. Numbers have meaning depending on their context. 

line-height

For example, when defining line-height, it is the ratio of the font-size.

p {
line-height: 1.5;
}

If the font size is 16px, then line height will be  16 × 1.5 = 24px.

2. Percentages

When using a percentage in CSS you need to know how the percentage is calculated.

width

For example, width is calculated as a percentage of the available width in the parent element. This makes percentage widths very useful for responsive layouts, because the element automatically adjusts when the parent container changes size.

div {
  width: 300px;
}
div p {
  width: 50%;
}

Here, the width of div p will be 150px.

3. Absolute Units

Absolute units have fixed values and do not change based on screen size or parent elements. Pixels (px) is the most common absolute unit.

.box {
  width: 300px;
  height: 200px;
}

Here, the box will always be 300 pixels wide and 200 pixels tall, regardless of screen size.

Absolute units can be used for borders, small elements and icons. However, relative units are better for responsive design.

4. Relative Units

Relative units adjust their size based on another element or the screen size.

  • The em unit is relative to the font size of its parent element.
  • The rem (root em) is relative to the root (html) font size, not the parent element.

5. Viewport Units

You can use the dimensions of the viewport (browser window) as a relative basis.

  • vw is 1% of viewport width
  • vh is 1% of viewport height
.hero {
  height: 100vh;
}

Here, the hero section will take the full height of the screen.