Back to Interview PrepGet interview ready with AILearn each topic the way interviewers ask it, then answer like you would in the interview.
Course progress0/13 chapters · 0%

Chapter 3 of 14

~11 min

Colors, Units & Values

CSS gives you several ways to express color and several kinds of units for size - picking the right one for the situation makes styles easier to reason about and to make responsive.

Color Formats

Named colors (tomato, dodgerblue) are readable but limited to a fixed palette. Hex codes (#1dbf73) are compact and precise. rgb()/rgba() and hsl()/hsla() let you express color as red/green/blue or hue/saturation/lightness, with an optional alpha channel for transparency - hsl() is often easier to reason about when you want to tweak lightness or saturation without changing the hue.

Try it yourself

<div class="named">named</div>
<div class="hex">hex</div>
<div class="rgb">rgb()</div>
<div class="rgba">rgba() - semi-transparent</div>
<div class="hsl">hsl()</div>

Output

Absolute vs Relative Units

px is an absolute unit - a fixed size regardless of context. em is relative to the font-size of the current element (or its parent, when used for font-size itself), which means it can compound unexpectedly when nested. rem is relative to the root element's font-size only, making it more predictable for consistent scaling across a whole page.

% is relative to the parent's corresponding dimension. vw and vh are relative to the viewport's width and height, which makes them useful for elements that should scale with the browser window itself, like a full-screen hero section.

Try it yourself

<p class="px">Sized with px</p>
<p class="rem">Sized with rem (1.5 * 16px root)</p>
<div class="vw">50% of the viewport width</div>

Output

currentColor

currentColor refers to an element's own computed color value, so you can reuse it for a border, background, or SVG fill without repeating the color or creating a separate variable - and it automatically updates if the color changes.

Try it yourself

<div class="box">Border matches text color automatically.</div>

Output

Coding challenge

Create a div with an hsla() background at 50% opacity and a border that uses currentColor.

<div class="box">Styled box</div>

Output

Answer every question below to mark this chapter as complete.

Quiz Yourself

Score: 0/4

1. Which unit is relative to the root element's font-size?

2. Which color function includes an alpha (transparency) channel alongside hue, saturation, and lightness?

3. What does 50vw mean?

4. What does the currentColor keyword do?

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in