</> Code Corner

CSS · CSS Tutorial · Lesson 38

CSS Units

Absolute and relative lengths: px, em, rem, %, vw, vh.

CSS has several units for expressing a length. There are two types: absolute and relative.

Unit Relative to
px Absolute pixels
em The font-size of the element (2em = 2x)
rem The font-size of the root element
% The parent element
vw / vh 1% of the viewport width / height
ch Width of the "0" character

Example

<style>
html { font-size: 16px; }
.px { font-size: 20px; }
.rem { font-size: 1.5rem; }
.em-parent { font-size: 20px; }
.em-parent span { font-size: 2em; }
.vw { width: 50vw; background: lightblue; }
</style>
<p class="px">20px text</p>
<p class="rem">1.5rem = 24px</p>
<p class="em-parent">Parent 20px, <span>child 2em = 40px</span></p>
<div class="vw">50vw wide</div>
Tip: Use rem for font sizes so the page respects the user's browser settings.

Keep reading “CSS Units”

Sign up to read the full lesson, try every example in the live editor, and take the 5-question quiz.

Chat with us 👋