CSS Units and Sizing Values
What Is It?
CSS lengths describe sizes and distances. Choose units according to what a size should relate to: a fixed CSS pixel, text size, a parent, or the viewport.
Properties, Tags and Attributes Explained
px: A CSS pixel, useful for borders and small fixed details.rem: Relative to the root element font size.em: For font-size, relative to the parent font size; for most other lengths, relative to the element font size.%: Relative to a property-specific reference, often the containing block.vw / vh: One percent of viewport width / height. dvh tracks the dynamic viewport height.
Each example is a complete HTML page. The CSS is inside the head's style element. Use Try in new tab to edit the CSS or HTML, run your changes, and reset the example.
Example 1: Relative text and spacing
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Units and Sizing Values</title>
<style>
.box { font-size: 1.25rem; padding: 1em; border: 2px solid #2563eb; }
</style>
</head>
<body>
<div class="box">Padding follows my font size.</div>
</body>
</html>Browser preview
What you see: The padding is one times the box font size.
Example 2: Fluid width
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Units and Sizing Values</title>
<style>
.track { background: #e2e8f0; }
.bar { width: 60%; padding: 12px; box-sizing: border-box; background: #bfdbfe; }
</style>
</head>
<body>
<div class="track"><div class="bar">60% width</div></div>
</body>
</html>Browser preview
What you see: The blue bar fills 60% of its parent width.
When and Where to Use It
Use rem for scalable typography and spacing, percentages for fluid widths, and pixels for fine borders.
Common Mistake or Useful Tip
A percentage height often needs a definite containing height. Unitless line-height is usually easier to inherit.
Try It Yourself
Change 60% to 80% and compare the result.