CSS Units

px, %, em, rem, vw, vh and more.

✍️ 3 exercises + code challenge in this lesson

CSS lengths can be absolute or relative.

Absolute

px (pixels) is the most common absolute unit.

Relative

  • %: relative to the parent element.
  • em: relative to the element's own font size.
  • rem: relative to the root (html) font size, usually 16px.
  • vw / vh: 1% of the viewport width / height.
  • ch: the width of the "0" character; great for limiting line length.

calc() mixes units: width: calc(100% - 40px);

Key Takeaways: CSS Units

Mastering CSS Units helps you write clean and reliable CSS code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

CSS Units Code Example

CSS
<style>
  div { background: #2563EB; color: white; margin: 6px 0; padding: 6px; }
  .px   { width: 200px; }
  .pct  { width: 60%; }
  .rem  { font-size: 1.5rem; }
  .vw   { width: 50vw; background: #14B8A6; }
  .calc { width: calc(100% - 80px); background: #071A2F; }
  .ch   { max-width: 30ch; background: #E34F26; }
</style>

<div class="px">200px</div>
<div class="pct">60%</div>
<div class="rem">1.5rem text</div>
<div class="vw">50vw</div>
<div class="calc">calc(100% - 80px)</div>
<div class="ch">max-width: 30ch keeps long lines short and readable.</div>
Free sign-in required · Google login available

CSS Units Practice Exercises

Check what you learned in “CSS Units”.

/ 3 solved
Fill in the blank

Set the font size relative to the root element.

p {
  font-size: 1.25;
}
✓ Correct! Not quite. Try again.
Multiple choice

What is 1rem when the html font size is 16px?

✓ Correct! Not quite. Try again.
Code challenge

Make the box half as wide as its parent using a percentage.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services