CSS Units Explained: px, em, rem, %, vh, vw, and More

In CSS, different units are used to define sizes, spacing, and positioning. Understanding the relationship between pixels and other CSS units like em, rem, %, vh, vw, etc., is essential for creating responsive and scalable designs.

1. Pixels (px)

A pixel (px) is a fixed unit that represents a single dot on the screen. It is not relative to the parent or viewport size.

Example: font-size: 16px; (Fixed size, does not scale with screen size)

2. Relative Units: em & rem

em (Relative to Parent Element)

The em unit is relative to the font-size of the parent element. If a parent has a font-size of 16px, then 1em equals 16px.

Example: padding: 2em; (If parent font-size is 20px, this equals 40px)

rem (Relative to Root Element)

The rem unit is based on the root html element’s font-size. By default, browsers set this to 16px.

Example: margin: 1.5rem; (Equals 24px if the root font-size is 16px)

3. Percentage (%)

The % unit is relative to the parent element’s dimensions. It is commonly used for widths, heights, and margins.

Example: width: 50%; (Element takes 50% of parent width)

4. Viewport Units: vh & vw

vh (Viewport Height)

The vh unit represents a percentage of the viewport height.

Example: height: 100vh; (Takes full height of the viewport)

vw (Viewport Width)

The vw unit represents a percentage of the viewport width.

Example: width: 50vw; (Takes half the width of the viewport)

Which CSS Unit Should You Use?

  • Use px for exact pixel-perfect designs.
  • Use em/rem for scalable and accessible typography.
  • Use % for flexible container sizes.
  • Use vh/vw for fullscreen elements.

Conclusion

Choosing the right CSS unit is crucial for responsive and accessible web design. Understanding how pixels relate to other units will help create adaptable layouts that look great on all devices.