Whenever you write a size in CSS, such as width: 300px or padding: 2rem, the part after the number is the unit. There are two families.
Absolute units
These are fixed. 1px is always 1px.
| Unit | Meaning |
|---|---|
px | A CSS pixel. The one you will use most |
cm, mm, in, pt | Real-world units, meant for print |
On screens, only px is common. A CSS pixel is not always one physical dot: on high-density phone screens, one CSS pixel is several dots, which is why a 16px font is still readable on a small phone.
Relative units
These depend on something else, which makes them flexible.
| Unit | Relative to |
|---|---|
% | The parent element’s size |
em | The font size of the element (or the parent, for font-size) |
rem | The font size of the root html element |
vw, vh | 1% of the viewport width / height |
vmin, vmax | 1% of the smaller / larger of the viewport’s dimensions |
fr | A share of leftover space in a grid |
<style>
.bar { background: #1a5276; color: #fff; padding: 6px; margin-bottom: 6px; }
</style>
<div class="bar" style="width: 200px">200px (fixed)</div>
<div class="bar" style="width: 50%">50% of the parent</div>
<div class="bar" style="width: 20em">20em (20 × font size)</div>
Zero doesn’t need a unit
margin: 0 is fine. Every other number needs a unit. margin: 10; is invalid and ignored.
Which should you use?
There is no single winner. In short: text and spacing in rem, widths in % or with max-width, full-screen sections with vh, and borders in px. The next lessons go through each one, and Choosing the Right Unit gives you the summary.
A space between number and unit
width: 20 px is invalid. Write 20px, with no space.