CSS Units

CSS units define the size of lengths, and they fall into two families: absolute units that stay fixed and relative units that scale with something else.

Almost every size in CSS, from font sizes to margins to widths, is a number paired with a unit. Choosing the right unit decides whether your layout stays rigid or adapts gracefully to different screens and user settings.

Absolute vs Relative

Absolute units are a fixed physical size and ignore their surroundings. Relative units are measured against another value, such as the parent's font size or the width of the viewport. See CSS Absolute Units and CSS Relative Units for more on each.

UnitRelative to
pxNothing; a fixed device pixel
%The parent element's size
emThe font size of the current element
remThe font size of the root html element
vw1% of the viewport width
vh1% of the viewport height

A Practical Mix

In real stylesheets you combine units: <rem> for type so it respects user preferences, <%> or <vw> for fluid widths, and <px> for hairline borders that should never change.

Mixing units sensibly

<!DOCTYPE html>
<html>
<head>
<style>
.card {
  width: 90%;
  max-width: 40rem;
  padding: 1.5rem;
  border: 1px solid #ddd;
  font-size: 1rem;
}
</style>
</head>
<body>

<div class="card">
  <h3>Plan Details</h3>
  <p>This card mixes percentage, rem, and pixel units.</p>
</div>

</body>
</html>

em Compounds, rem Does Not

Root-relative sizing

<!DOCTYPE html>
<html>
<head>
<style>
html {
  font-size: 16px;
}

h1 {
  font-size: 2rem;   /* 32px */
}

p {
  font-size: 1rem;   /* 16px */
}
</style>
</head>
<body>

<h1>Page Title</h1>
<p>This paragraph uses the root font size.</p>

</body>
</html>
Note: Use rem for font sizes so text scales when a user increases their browser's default font size, which px would ignore.

Exercise: CSS Units

Why is the em unit described as 'compounding' when nested elements each set font-size in em?