Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Teachable.

Length units – CSS

Summary

The most common length units in CSS are px, percentages, ems, rems, vh, and vw. These length units are used with values for properties like font-size, margin, padding, border-width, and others.

Details

px

A pixel is an absolute length unit. It’s the easiest unit to use and the one we’ll use in most of our examples on Simple Dev.

em and rem

The next two examples use the following HTML code:

<!doctype html>
<html>
  <head>
    <!-- meta stuff goes here... -->
  </head>
  <body>
    <div>
      <p>Hello world!</p>
    </div>
  </body>
</html>

An em is a multiple of the font-size value of the parent element. Let’s say we added the following CSS rule to the code above:

div {
  font-size: 20px;
}

p {
  font-size: 2em;
}

The resulting font-size of the paragraph would be calculated by multiplying the font-size of the parent element (which in this case is the div element) by 2. The result would be 40px.

A rem is a multiple of the font-size value of the root element. The root element is usually the html element. If we added the following rules to the CSS code from above:

html {
  font-size: 10px;
}

p {
  font-size: 2rem;
}

The resulting font-size of the paragraph would be calculated by multiplying the font-size of the html element, 10px, by 2. The result would be 20px.

vh and vw

The vh and vw units represent 1% of the height and width of the viewport’s initial containing block, respectively.


To see a list of all of the length units available in CSS, click the link in the References section.

Exercises

There are no exercises for this lesson.

References

The <length> data type on MDN

Back to: CSS Reference > CSS Values