The unit you choose in CSS matters a lot for responsive design. Pixels are fixed, but the viewport changes. If you use only pixels, your design will not adapt. That is where relative units come in.
Percentages
Percentages are relative to the parent element. A child with width: 50% takes
up half of its parent's width.
.container {
width: 80%; /* 80% of the body */
max-width: 1200px; /* but never wider than 1200px */
}
This is a classic pattern: the container takes up 80% of the screen, but stops growing at 1200px on large monitors.
Try it Yourself →Viewport Units — vw and vh
vw (viewport width) and vh (viewport height) are relative to
the browser window itself, not the parent element.
.hero {
height: 100vh; /* exactly the height of the viewport */
width: 100vw; /* exactly the width of the viewport */
}
.half-width {
width: 50vw; /* half the viewport width */
}
100vh is perfect for full-screen hero sections. The section always fills
the entire screen no matter what device you are on.
vmin and vmax
vmin is whichever is smaller — vw or vh. vmax is whichever
is larger. These are great for things that should scale with the smaller dimension.
.square {
width: 50vmin;
height: 50vmin;
/* always a square, scaled to the smaller viewport side */
}
Em and Rem
em is relative to the element's font size. rem is relative to
the root font size (usually html). The difference matters a lot.
html {
font-size: 16px;
}
.container {
font-size: 20px;
padding: 1em; /* 20px — relative to container font */
}
.global-padding {
padding: 1rem; /* 16px — always relative to root */
}
rem is more predictable because it is always based on the root size.
em compounds — if a parent has font-size: 1.5em and its child
also has font-size: 1.5em, the child ends up 2.25 times the base size.
Choosing the Right Unit
Here is a quick guide:
px— borders, shadows, tiny details that should not change%— widths, fluid layoutsvw/vh— full-screen sections, hero imagesrem— font sizes, spacing that should scale consistentlyem— padding/margin relative to the element's font size
Most modern CSS uses a mix of rem for typography, % for widths,
and px for tiny UI details.