In CSS, units define the size of elements – whether it’s width, height, font size, or spacing. Understanding CSS units is essential for creating flexible and responsive designs that look good across different devices.
What Are CSS Units?
CSS units determine how measurements are applied in your design. They can be absolute (fixed values like px
) or relative (values that adapt based on the parent element, root element, or viewport size).
Example:
p {
font-size: 16px; /* Absolute unit */
margin: 5%; /* Relative unit */
}
Absolute Units
Absolute units are fixed and do not change based on the screen or parent element.
- px (pixels) → Most commonly used, fixed size.
- cm, mm, in, pt, pc → Rarely used in web design (more for print).
Example:
div {
width: 200px;
height: 100px;
}
👉 The size will stay the same on all screens.
Relative Units
Relative units adjust based on parent element, root element, or viewport. They make designs flexible and responsive.
a) Percentage (%
)
Relative to the parent element’s size.
div {
width: 80%; /* 80% of parent width */
}
b) em
Relative to the font-size of the parent element.
p {
font-size: 1.5em; /* 1.5 × parent’s font size */
}
c) rem (root em)
Relative to the font-size of the root element (html
).
html {
font-size: 16px;
}
p {
font-size: 2rem; /* 2 × 16px = 32px */
}
👉 More consistent than em
because it always refers to the root.
Viewport Units
Viewport units adjust based on the size of the browser window.
- vw = 1% of viewport width
- vh = 1% of viewport height
- vmin = smaller of vw or vh
- vmax = larger of vw or vh
Example:
div {
width: 50vw; /* 50% of browser width */
height: 50vh; /* 50% of browser height */
}
👉 Useful for fullscreen layouts and responsive typography.
Combining Units
You can mix units to create balanced, responsive designs.
Example:
div {
width: 80%;
padding: 2rem;
font-size: 1.2em;
}
Common Mistakes Beginners Make
- Using only
px
→ makes layouts non-responsive. - Confusing
em
andrem
. - Forgetting that
%
depends on parent element size. - Overusing
vh
andvw
→ can cause overflow issues on small screens.
Quick Reference Summary
Unit | Type | Relative To | Example |
---|---|---|---|
px | Absolute | Fixed pixels | width: 200px; |
% | Relative | Parent element | width: 80%; |
em | Relative | Parent’s font-size | font-size: 1.5em; |
rem | Relative | Root font-size (html ) | font-size: 2rem; |
vw | Relative | Viewport width | width: 50vw; |
vh | Relative | Viewport height | height: 100vh; |
vmin | Relative | Smaller of vw/vh | font-size: 5vmin; |
vmax | Relative | Larger of vw/vh | font-size: 5vmax; |
Practice Challenge
- Set the
html
font-size to16px
. - Create a
<div>
with:width: 60%
padding: 2rem
font-size: 1.5em
- Add a header with
font-size: 5vw
so it scales with browser width.
Conclusion
By mastering CSS units, you can create designs that are both precise and adaptable. Use absolute units (px
) for fixed elements, and relative/viewport units (%
, em
, rem
, vh
, vw
) for responsive layouts.