Bird
Raised Fist0
CSSmarkup~15 mins

Relative units in CSS - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Relative units
What is it?
Relative units in CSS are measurements that depend on something else, like the size of the parent element or the user's screen. Unlike fixed units such as pixels, relative units change based on context, making designs flexible. They help create layouts that adapt to different devices and user settings. This means your website can look good on a phone, tablet, or big monitor without extra work.
Why it matters
Without relative units, websites would be rigid and hard to read on different screens. Fixed sizes can make text too small or too big, breaking the design or hurting accessibility. Relative units solve this by letting elements grow or shrink naturally. This improves user experience, saves time for developers, and makes websites future-proof as new devices appear.
Where it fits
Before learning relative units, you should understand basic CSS units like pixels and how CSS properties control layout and size. After mastering relative units, you can explore responsive design techniques, CSS Grid and Flexbox layouts, and accessibility best practices to build flexible, user-friendly websites.
Mental Model
Core Idea
Relative units measure size based on something else, making web designs flexible and adaptable to different screens and user settings.
Think of it like...
Think of relative units like clothing sizes that adjust based on the person wearing them, instead of fixed sizes that only fit one person perfectly.
┌───────────────────────────────┐
│          Relative Units        │
├───────────────┬───────────────┤
│ Unit Type     │ Reference     │
├───────────────┼───────────────┤
│ em            │ Parent font   │
│ rem           │ Root font     │
│ %             │ Parent size   │
│ vw/vh         │ Viewport size │
│ vmin/vmax     │ Viewport min/max│
└───────────────┴───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding fixed vs relative units
🤔
Concept: Introduce the difference between fixed units like pixels and relative units that depend on other sizes.
Fixed units like pixels (px) always stay the same size no matter where they are used. For example, 20px is always 20 pixels on the screen. Relative units change size depending on something else, like the size of the parent element or the screen size. This means they can grow or shrink to fit different devices or user preferences.
Result
Learners can distinguish fixed units from relative units and understand why fixed units can cause problems on different screens.
Understanding the difference between fixed and relative units is key to making flexible, accessible web designs that work well everywhere.
2
FoundationCommon relative units in CSS
🤔
Concept: Learn the main relative units used in CSS and what they depend on.
The most common relative units are: - em: relative to the font size of the parent element - rem: relative to the root (html) font size - %: relative to the size of the parent element - vw/vh: relative to 1% of the viewport's width or height - vmin/vmax: relative to the smaller or larger of vw and vh These units let you size text, boxes, and spacing in ways that adapt to context.
Result
Learners can identify and explain the main relative units and their references.
Knowing these units and their references helps you choose the right one for flexible and consistent designs.
3
IntermediateUsing em and rem for scalable typography
🤔Before reading on: do you think em and rem always produce the same size? Commit to your answer.
Concept: Explore how em and rem units work differently for font sizing and why that matters.
em units scale based on the font size of the parent element. This means if a parent has font-size 20px, 1em inside it equals 20px. But if a child element also sets font-size in em, sizes multiply, which can cause unexpected results. rem units always refer to the root font size (usually set on the html element). This makes rem more predictable for consistent sizing across the page. Example: html { font-size: 16px; } .parent { font-size: 1.25em; /* 20px */ } .child { font-size: 1em; /* 20px if em, but 16px if rem */ }
Result
Learners understand how em can compound sizes while rem stays consistent, helping them pick the right unit for typography.
Understanding the difference between em and rem prevents common bugs in font scaling and helps create predictable, accessible text sizes.
4
IntermediatePercentages for flexible layouts
🤔Before reading on: does 50% width always mean half the screen width? Commit to your answer.
Concept: Learn how percentage units depend on the parent element's size, not always the screen.
Percentages in CSS measure size relative to the parent element's size. For example, width: 50% means half the width of the parent container, not necessarily half the screen. This lets you create flexible layouts that adjust as containers resize. Example: .container { width: 400px; } .box { width: 50%; /* 200px */ } If the container changes size, the box adjusts automatically.
Result
Learners can use percentages to build layouts that adapt to container sizes, not just the screen.
Knowing that percentages depend on parent size helps avoid layout surprises and enables responsive design.
5
IntermediateViewport units for screen-relative sizing
🤔Before reading on: does 10vw equal 10% of the screen width or the parent element? Commit to your answer.
Concept: Understand viewport units vw, vh, vmin, vmax and how they relate to the visible screen size.
Viewport units measure size relative to the browser window: - 1vw = 1% of viewport width - 1vh = 1% of viewport height - vmin = smaller of vw or vh - vmax = larger of vw or vh These units help size elements based on the visible screen, useful for full-screen layouts or responsive typography. Example: .box { width: 50vw; height: 50vh; } /* half screen width and height */
Result
Learners can use viewport units to size elements relative to the screen, improving responsiveness.
Using viewport units lets designs respond directly to screen size, essential for mobile-friendly layouts.
6
AdvancedCombining relative units for responsive design
🤔Before reading on: can combining em, rem, %, and vw units create more flexible layouts? Commit to your answer.
Concept: Learn how mixing different relative units can solve complex layout and typography challenges.
By combining units, you can create designs that adapt smoothly: - Use rem for base font size to keep text consistent - Use em for spacing inside components that scale with text - Use % for widths inside flexible containers - Use vw for large headings that scale with screen size Example: html { font-size: 16px; } h1 { font-size: 5vw; margin-bottom: 1em; } .container { width: 80%; padding: 2rem; } This approach balances consistency and flexibility.
Result
Learners see how combining units creates adaptable, readable, and visually balanced designs.
Knowing how to mix units unlocks powerful responsive design techniques beyond simple fixed or single-unit layouts.
7
ExpertUnexpected pitfalls with relative units
🤔Before reading on: do you think using em units inside nested elements always scales predictably? Commit to your answer.
Concept: Explore subtle issues like compounding em units, inheritance quirks, and browser differences.
em units multiply when nested, which can cause sizes to grow or shrink unexpectedly if not managed carefully. Inheritance means font sizes cascade down, so changing one parent can affect many children. Some browsers handle rounding of relative units differently, causing slight layout shifts. Example problem: .parent { font-size: 1.2em; } .child { font-size: 1.2em; } /* actually 1.44 times root size */ To avoid this, use rem for global sizes and em for local adjustments. Also test designs on multiple browsers and devices.
Result
Learners become aware of subtle bugs and how to avoid them for robust, maintainable CSS.
Understanding these pitfalls prevents frustrating bugs and helps write clean, predictable CSS that works everywhere.
Under the Hood
Relative units are calculated by the browser during rendering. For em and %, the browser looks up the computed size of the parent element or root element and multiplies by the relative value. Viewport units are calculated based on the current size of the browser window. These calculations happen dynamically, so if the window resizes or user changes font settings, the browser recalculates sizes and updates the layout instantly.
Why designed this way?
Relative units were created to solve the problem of fixed, inflexible layouts that break on different devices or user settings. Early web pages used pixels only, which made designs rigid. Relative units allow designs to adapt naturally, improving accessibility and user experience. The choice of references (parent, root, viewport) reflects common needs: scaling with text, consistent base sizes, or adapting to screen size.
┌───────────────┐
│   CSS Rule    │
│ font-size: 2em│
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Parent font   │
│ size = 16px   │
└──────┬────────┘
       │ multiply
       ▼
┌───────────────┐
│ Computed size │
│ 2 × 16px = 32px│
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does 1em always equal 16px regardless of context? Commit to yes or no.
Common Belief:Many believe 1em is always 16 pixels, the default browser font size.
Tap to reveal reality
Reality:1em equals the font size of the parent element, which can be different from 16px if the parent changes size.
Why it matters:Assuming 1em is fixed causes unexpected sizing bugs, especially in nested elements where sizes compound.
Quick: Does 50% width always mean half the screen width? Commit to yes or no.
Common Belief:Some think percentage widths are always relative to the entire screen width.
Tap to reveal reality
Reality:Percentages are relative to the parent element's size, not the screen, so the actual pixel size depends on the container.
Why it matters:Misunderstanding this leads to broken layouts when containers resize or are nested.
Quick: Are viewport units (vw, vh) affected by parent element sizes? Commit to yes or no.
Common Belief:People sometimes believe viewport units depend on parent elements like em or % units.
Tap to reveal reality
Reality:Viewport units always relate to the browser window size, ignoring parent elements.
Why it matters:Confusing viewport units with relative units can cause layout errors and unexpected element sizes.
Quick: Does using rem units always fix scaling issues with nested elements? Commit to yes or no.
Common Belief:Some think rem units solve all scaling problems and can be used everywhere without issues.
Tap to reveal reality
Reality:While rem units provide consistency, they don't adapt to local context, which can reduce flexibility in some designs.
Why it matters:Overusing rem can make designs less adaptable to user preferences or component-level scaling needs.
Expert Zone
1
em units compound in nested elements, so careful management is needed to avoid exponential scaling.
2
Using rem units allows global control of font size by changing only the root font size, enabling easy theming or accessibility adjustments.
3
Viewport units can cause layout shifts on mobile browsers when UI chrome (address bar) shows or hides, requiring special handling.
When NOT to use
Relative units are not ideal when exact pixel precision is required, such as for pixel-perfect graphics or icons. In those cases, fixed units like pixels or SVG vector graphics are better. Also, avoid mixing too many relative units in deeply nested elements to prevent unpredictable scaling.
Production Patterns
Professionals use rem units for base font sizes and em units for component spacing to maintain scalability. Viewport units are common for hero sections or full-screen layouts. Percentages are widely used in grid and flexbox layouts for flexible widths. Combining these units with media queries creates responsive designs that adapt smoothly across devices.
Connections
Responsive Web Design
Relative units are foundational tools used to build responsive layouts that adapt to different screen sizes.
Mastering relative units enables creating fluid designs that respond naturally to device changes, a core principle of responsive design.
Accessibility (a11y)
Relative units allow users to adjust text size via browser settings, improving readability and accessibility.
Using relative units respects user preferences and helps meet accessibility standards, making websites usable for more people.
Music Dynamics
Just as relative units adjust size based on context, music dynamics change volume relative to the surrounding sounds.
Understanding relative scaling in CSS is like understanding how music adapts volume to fit the environment, showing how context shapes perception.
Common Pitfalls
#1Using em units inside nested elements without control causes unexpected size multiplication.
Wrong approach:.parent { font-size: 1.2em; } .child { font-size: 1.2em; }
Correct approach:.parent { font-size: 1.2em; } .child { font-size: 1rem; }
Root cause:Misunderstanding that em units multiply based on the parent's computed font size, leading to exponential growth.
#2Assuming percentage widths are relative to the viewport instead of the parent container.
Wrong approach:.container { width: 50%; } /* expecting 50% of screen width */
Correct approach:.container { width: 50vw; } /* 50% of viewport width */
Root cause:Confusing percentage units with viewport units, leading to layout that doesn't behave as expected.
#3Using viewport units for font size without considering mobile browser UI changes causes layout shifts.
Wrong approach:h1 { font-size: 10vw; }
Correct approach:h1 { font-size: clamp(1.5rem, 10vw, 3rem); }
Root cause:Not accounting for dynamic viewport height changes on mobile browsers, causing text to resize unexpectedly.
Key Takeaways
Relative units in CSS let you create flexible, adaptable designs that respond to different devices and user settings.
em units scale relative to the parent element's font size, which can compound in nested elements, while rem units always refer to the root font size for consistency.
Percentages depend on the size of the parent container, not the screen, making them ideal for flexible layouts within containers.
Viewport units measure size relative to the visible browser window, useful for full-screen or responsive sizing but require careful handling on mobile.
Combining different relative units thoughtfully unlocks powerful responsive design techniques, but be aware of pitfalls like compounding sizes and browser quirks.

Practice

(1/5)
1. Which CSS unit is relative to the root element's font size?
easy
A. em
B. rem
C. px
D. vw

Solution

  1. Step 1: Understand root-relative units

    The rem unit always refers to the font size set on the root <html> element.
  2. Step 2: Compare with other units

    em is relative to the parent element's font size, px is fixed pixels, and vw is relative to viewport width.
  3. Final Answer:

    rem -> Option B
  4. Quick Check:

    Root font size = rem [OK]
Hint: Root font size uses rem, not em or px [OK]
Common Mistakes:
  • Confusing em with rem
  • Thinking px is relative
  • Mixing viewport units with font units
2. Which of the following is the correct syntax to set a font size to 2 times the parent element's font size?
easy
A. font-size: 2vw;
B. font-size: 2rem;
C. font-size: 2px;
D. font-size: 2em;

Solution

  1. Step 1: Identify the unit for parent-relative size

    em units scale relative to the parent element's font size.
  2. Step 2: Check other options

    rem is root-relative, px is fixed, and vw is viewport width relative.
  3. Final Answer:

    font-size: 2em; -> Option D
  4. Quick Check:

    Parent-relative font size = em [OK]
Hint: Use em for parent-relative sizes, rem for root-relative [OK]
Common Mistakes:
  • Using rem instead of em for parent size
  • Using px which is fixed size
  • Confusing vw with font size units
3. Given the CSS below, what will be the width of the <div> if the viewport width is 1000px?
div {
  width: 50vw;
}
medium
A. Depends on parent width
B. 50px
C. 500px
D. 1000px

Solution

  1. Step 1: Understand vw unit

    1vw equals 1% of the viewport width. So 50vw is 50% of viewport width.
  2. Step 2: Calculate width

    Viewport width is 1000px, so 50vw = 50% of 1000px = 500px.
  3. Final Answer:

    500px -> Option C
  4. Quick Check:

    50vw = 50% viewport width = 500px [OK]
Hint: vw is % of viewport width, multiply by viewport size [OK]
Common Mistakes:
  • Thinking vw depends on parent width
  • Confusing vw with px
  • Calculating 50vw as 50px
4. What is wrong with this CSS if the goal is to make the font size 1.5 times the parent font size?
p {
  font-size: 1.5rem;
}
medium
A. rem is root-relative, not parent-relative
B. 1.5rem is invalid syntax
C. font-size cannot use rem units
D. Should use px instead of rem

Solution

  1. Step 1: Identify unit behavior

    rem units are relative to the root font size, not the parent element.
  2. Step 2: Match goal with unit

    To scale relative to the parent font size, em should be used instead of rem.
  3. Final Answer:

    rem is root-relative, not parent-relative -> Option A
  4. Quick Check:

    Parent-relative size needs em, not rem [OK]
Hint: Use em for parent-relative font size, not rem [OK]
Common Mistakes:
  • Thinking rem scales with parent
  • Believing 1.5rem is invalid syntax
  • Using px for scalable font sizes
5. You want a button width to be 30% of the viewport width but never smaller than 200px. Which CSS snippet correctly uses relative units and a minimum width?
hard
A. button { width: 30vw; min-width: 200px; }
B. button { width: 30%; min-width: 200vw; }
C. button { width: 30rem; min-width: 200px; }
D. button { width: 30em; min-width: 200%; }

Solution

  1. Step 1: Understand width units

    30vw means 30% of viewport width, which matches the requirement.
  2. Step 2: Check minimum width

    min-width: 200px ensures the button never shrinks below 200 pixels.
  3. Step 3: Verify other options

    Other options fail: 30rem is root font-relative; 30% with min-width: 200vw uses parent-relative width and huge min-width; 30em with min-width: 200% uses font-relative and parent-relative units incorrectly.
  4. Final Answer:

    button { width: 30vw; min-width: 200px; } -> Option A
  5. Quick Check:

    30vw + min-width: 200px [OK]
Hint: Use vw for viewport %, min-width in px for fixed minimum [OK]
Common Mistakes:
  • Using % for viewport width instead of vw
  • Setting min-width in vw or % incorrectly
  • Confusing rem/em with viewport units