CSS Units: px, %, em, and rem


CSS units control the size of text, boxes, spacing, and layouts.

Choosing the right unit is important for good design and responsiveness.

Types of CSS Units

CSS units are mainly divided into:

  • Absolute units
  • Relative units

Absolute Units

Absolute units stay the same size.

The most common absolute unit is pixel (px).

This creates a box with a fixed size.

Relative Units

Relative units change size based on something else.

They are better for responsive designs.

Percent (%)

Percent is relative to the size of the parent element.

This makes the container take 80 percent of its parent width.

em Unit

em is relative to the font size of the parent element.

This sets padding based on text size.

rem Unit

rem is relative to the root element font size.

It is more predictable than em.

This makes the heading size consistent everywhere.

Comparing Units

px:

  • Fixed size
  • Not flexible

%:

  • Relative to parent
  • Flexible

em:

  • Relative to parent font size
  • Can grow quickly

rem:

  • Relative to root font size
  • Easy to manage

When to Use Each Unit

  • Use px for borders and small details
  • Use % for layout widths
  • Use em for spacing near text
  • Use rem for font sizes

Why This Matters for Jobs

Professional developers use relative units to build responsive websites.

Knowing units makes your layouts flexible and future-proof.

Common Beginner Mistakes

  • Using only px everywhere
  • Confusing em and rem
  • Not testing layouts on different screen sizes

Practice Task

Try this:

  1. Create a box using px
  2. Create another using %
  3. Set text size using rem
  4. Add padding using em

What You Will Learn Next

In the next lesson, you will learn about viewport units like vw and vh.