E-Learning Platform
Web Foundation I

Colors & Units

TeachesColor valuesLength units

Last lesson you learned to aim a rule — a selector that picks out p or .highlight. This lesson is about what goes after the colon: the values themselves, starting with the two you'll reach for constantly, color and size.

Color, three ways

CSS gives you three ways to write the same color. Think of it like a date: "12/25", "December 25th", and "the 359th day of the year" all name the same day. These three name the same shade of blue:

.badge { color: navy; }
.badge { color: #000080; }
.badge { color: rgb(0, 0, 128); }

A named keyword (navy) is the easiest to read. A hex code (#000080) packs red, green, and blue into three pairs of digits — you'll meet these constantly once you start copying colors from design tools. An rgb() function spells the same three numbers out in plain sight. Pick whichever you can read fastest; the browser treats them as identical.

Color isn't only for text. background-color paints the element's own box instead of its words:

.badge { background-color: lightyellow; }

Sizing things: px and %

Two units cover most of what you'll need for now. px (pixels) is a fixed, exact size — 300px is 300px, wherever it appears. % is relative — a fraction of whatever box wraps it, not a fixed answer on its own:

.frame { width: 300px; }
.frame .badge { width: 50%; }

.badge here becomes 150px wide — because its parent, .frame, is 300px. Resize .frame to 600px and .badge follows it to 300px, without touching .badge's own rule at all. That's the whole point of a percentage: it describes a relationship, not a fixed number.

Common mistake

It's easy to forget that a percent always means "relative to whatever wraps it" — not the whole page. A width: 50% inside a narrow parent produces a narrow result, even if the rest of the page has plenty of room. If a percentage size looks wrong, the first thing to check is the size of the element around it.

Color and size are the two values you'll write most often from here on. Next up: doing the same for the words themselves — typeface, size, and weight.

Exercise

Style a distance badge

Below is a small frame with a distance badge inside it. Style it:

- .framewidth: 300px; and background-color: lightyellow;. - .badgewidth: 50%; (half of .frame's width) and color: navy;.

Try writing the colors as named keywords first — lightyellow and navy — the same way the lesson showed hex and rgb() as alternate spellings for the same colors, if you'd rather practice those instead.