CSS units define how sizes like width, height, margin, padding, and font-size are measured on a web page.
Units can be:
px, cm).%, em, rem, vw, vh).Choosing the right unit is a key step in building responsive, accessible layouts.
px) are fixed and great for borders or tiny icons, but not ideal for full layouts.%) depend on the size of the parent element.em is relative to the font size of the current element’s parent.rem is relative to the font size of the root element (<html>).vw / vh are based on the viewport width and height.cm, mm, and in are rarely used on screens.| Unit | Type | Description | Example |
|---|---|---|---|
px |
Absolute | Pixels – fixed size | width: 200px; |
% |
Relative | Percentage of parent | width: 50%; |
em |
Relative | Relative to parent font size | font-size: 1.5em; |
rem |
Relative | Relative to root font size | padding: 2rem; |
vw |
Relative | Viewport width | width: 50vw; |
vh |
Relative | Viewport height | height: 80vh; |
cm, mm, in |
Absolute | Physical units (not often used) | width: 5cm; |
A typical CSS declaration uses a property, a colon, a value with unit, and ends with a semicolon:
property: value<unit>;
width: 200px; → the box is exactly 200 device pixels wide.width: 50%; → the box takes half of its parent’s width.font-size: 1.5rem; → 1.5 × the root font size (often 16px → 24px).width: 50vw; → half of the viewport width.Using relative units (%, rem, vw, etc.) makes your design scale better across different screens and zoom levels.
The following example compares a fixed-width box using px, a fluid box using %, and text sized with rem.
/* Compare px, %, and rem based sizing */
.container-demo {
width: 80%;
max-width: 800px;
margin: 0 auto;
}
.box-px {
width: 200px;
height: 80px;
background: #bfdbfe;
}
.box-percent {
width: 50%;
height: 80px;
background: #bbf7d0;
}
.text-rem {
font-size: 1.5rem;
padding: 1rem 5%;
background: #fecaca;
}
Imagine the following sample layout inside a container. The first box uses a fixed pixel width, the second uses a percentage, and the text uses rem for scalable sizing.
If the container becomes narrower (like on mobile), the pixel box keeps its exact width, while the percentage box shrinks or grows with the container.
Text using rem automatically scales when the user changes the browser’s base font size, improving accessibility.
rem for font sizes and spacing so the entire design scales consistently.% for fluid layouts, especially for widths in responsive grid or flexbox layouts.px for tiny elements like borders, icons, or shadows.padding: 1rem 5%; for consistent vertical and flexible horizontal spacing.vw and vh carefully; test on small screens to avoid oversized elements.width: 100vw; and a fixed-height banner using 40vh.200px wide and another 50% wide. Resize the browser and compare.html { font-size: 16px; }) and style text using only rem.rem (top/bottom) and % (left/right).vw for responsive headline text (for example, font-size: 5vw;) and observe behaviour.