CSS sizes need a unit (except 0).
Absolute unit
px— pixels. Fixed size.
Relative units
| Unit | Relative to |
|---|---|
% |
the parent element |
em |
the element's own font size |
rem |
the root (html) font size, usually 16px |
vw |
1% of the viewport width |
vh |
1% of the viewport height |
Which to use?
remfor font sizes and spacing (respects user settings)%orvwfor flexible widthspxfor thin borders and small details
Example
Example — Comparing units
HTML
<style>
.px { font-size: 20px; }
.rem { font-size: 1.5rem; }
.half { width: 50%; background: #dbe8ff; padding: 8px; }
.vw { width: 30vw; background: #ffe2d6; padding: 8px; margin-top: 8px; }
</style>
<p class="px">20px text</p>
<p class="rem">1.5rem text (24px)</p>
<div class="half">50% of parent width</div>
<div class="vw">30vw of the window</div>