All topics › Unit 3 · Cascading Style Sheets
Topic 25 · 25 of 43
Units and Measurements
All in one: every unit of this chapter, side by side
What this example compares
- A number needs a unit:
font-size: 20vs20px,width: 100vs100px, andmargin: 0, the only bare number - Absolute vs relative: the same
10inpx,%,em,rem,vwandvh - px: the 25.2
.box,1pxand2pxborders, a small shadow - %:
width: 50%of a wide and a 260px parent,100%, and the height trap (height: 50%vs a parent height vsmin-heightvsvh) - em:
0.5emvs1emvs2emin 20px text - Padding:
padding: 0.6em 1.2emfollows the text,11px 22pxdoes not - Nesting:
1.5emmultiplies (24, 36, 54px) vs1.5remstays 24px - rem sizes:
0.875rem,1rem,1.25rem,1.5rem,2rem= 14 to 32px - Who decides the text size:
20pxvs1.25remand the roothtml { font-size: 100%; } - The window:
20%vs20vw, and the 25.6 welcome panel (60vh,4vw) in a toy phone and a toy laptop - auto:
margin: 0 autovsmargin: 0,height: autovsheight: 40px - ch and fr:
max-width: 65ch,width: 10ch,1fr 1frvs1fr 2frvs60px 1fr - Formulas:
calc(100% - 40px)vscalc(100%-40px)vsclamp(1rem, 2.5vw, 2rem) - Which unit?: the project, step 4, with every unit in its right place
Point at any word in the code to see what it means (tap on a phone); click a word to keep its meaning on screen. Read the comment above each numbered panel, press Run, then Edit & experiment to try the TRY lines yourself.
Loading the example…
What you should see
You should see fourteen panels, each card with a small dark tag giving its real size. In panel 1 "Twenty?" stays at 16px while "Twenty!" is 20px, and the strip without a unit fills its card. Panel 2 shows six strips of very different lengths, all written as width: 10. In panel 4 the same 50% bar is wider in the wide parent than in the 260px one (130px), and height: 50% does nothing until the parent has a height. Panel 5 shows squares of 10, 20 and 40px, panel 6 a cramped third button, and panel 7 text growing 24, 36, 54px on the left but staying 24px on the right. Panel 8 reads 14, 16, 20, 24 and 32px. Panel 10 shows the same welcome panel in two little windows: tiny 6.8px text in the toy phone, 12px in the toy laptop. In panel 11 the first box is centred and the last one's text spills out; panel 13's wrong calc() strip is full width. The Console prints the window size, the root font size (16px) and one line per measured box; the %, vw and vh numbers depend on how big your result frame is, the px, em and rem numbers do not.
Quick check: in panel 7, why does Level 3 come out at 54px on the left but 24px on the right, when both say 1.5?
On the left the font size is in em, measured against the parent's font size, so the factors multiply: 16 × 1.5 = 24, × 1.5 = 36, × 1.5 = 54. On the right it is in rem, always measured against the one root size of 16px, so every level is 16 × 1.5 = 24px.