Unit | Relative To | Best For |
---|---|---|
px |
Device Screen | Fixed-size elements, border , box-shadow . |
rem |
Root (<html> ) font-size |
Modern standard. font-size , margin , padding , most layout values. |
em |
Parent element’s font-size | Sizing elements relative to their own font-size (e.g., padding on a button). |
vh /vw |
Viewport height & width | Full-screen sections, elements sized relative to window height or width. |
% |
Parent element’s size | Responsive layouts, sizing elements inside a container. |
For most projects, a good strategy is:
rem
for font sizes and spacing (margin
, padding
).px
for tiny, non-scalable values like border widths.%
, vw
, or vh
for high-level layout containers.<div style="font-size: 1.2rem;">
<!-- Computes to 1.2 * 16px = 19.2px -->
<div style="font-size: 1.2em;">
<!-- Computes to 1.2 * 19.2px = 23.04px -->
Some text.
</div>
</div>
Absolute units are fixed and do not change based on any other element’s size or screen settings. The most common absolute unit is the pixel (px
).
px
(Pixels)1px
is one dot on your display.px
when you need a fixed size that should not scale. It’s great for things like borders (border: 1px solid black;
) or box-shadows where you want a crisp, consistent line.px
for everything, especially for font sizes and spacing, can harm accessibility. Users who have set a larger default font size in their browser will not see px
based text scale up, making it harder to read.Relative units are flexible because they are measured in relation to another value. This makes them ideal for building responsive and accessible websites.
rem
(Root em
)<html>
tag).font-size
of the <html>
element. The browser default is typically 16px
, so by default, 1rem = 16px
.