CSS Units: How To Use px, em, rem, pt and more

Introduction

Whether you're just starting out in web development or have been coding for years, working with CSS units can be tricky. With so many options - px, em, rem, vw, vh, %, pt, ex, ch, and more - it's easy to get confused about which units to use and when.

In this comprehensive guide, we'll explain all the different CSS units available and how to use them properly. We'll look at length units like px, em, and rem, viewport units like vw and vh, percentage values, and several others. There are lots of code examples throughout to help cement your understanding.

Let's dive in!

Absolute Length Units

Absolute length units represent an actual, fixed length that doesn't scale or adapt based on other parameters. The most common absolute CSS units are:

Pixel (px)

The pixel is the most widely used unit in CSS and represents a single dot on your screen. Pixels give you absolute control over element sizes:

div {
  width: 200px;
  height: 100px;
}

This div will always be exactly 200px wide and 100px tall, regardless of any other styling.

Pixels work great for borders, padding, font-sizes, and any other elements where you want a precise, consistent size. But they can cause accessibility issues if used improperly for things like font sizes, since users can't scale the elements.

Centimeter (cm)

The centimeter is based on the physical centimeter unit, defined as 1/100th of a meter. It is rarely used for web design, but can be useful for print styles:

div {
  width: 5cm;
}

Millimeter (mm)

The millimeter is 1/10th of a centimeter. It has the same use cases as cm but allows for finer precision:

p {
  margin-bottom: 5mm; 
}

Inch (in)

The inch unit converts to 96px, which is the default pixel density of most displays.

img {
  width: 3in; // 296px
}

Using inches can make sense for print media where px don't map cleanly to real-world sizes.

Point (pt)

A point equals 1/72nd of an inch. Points are traditionally used in print design and typography:

h2 {
  font-size: 20pt;
} 

Pica (pc)

A pica is 12 points, so there are 6 picas per inch. Picas were used in typesetting to calculate line lengths and spacing.

p {
  column-width: 3pc; 
}

Picas aren't commonly used on the web today. But they can be handy for print media conversions.

As you can see, absolute CSS units like px and in are fixed and don't scale in fluid ways. Next let's look at relative units.

Relative Length Units

Relative units are sized relative to something else, like the parent element size or viewport dimensions. Some common relative CSS units are:

Em

The em is based on the font-size of the parent element. For example, with this CSS:

.parent {
  font-size: 16px;
}

.child {
  font-size: 2em; // 32px 
}

The child element computes to 2 * 16px = 32px. This makes ems useful for maintaining consistent typographic scales and proportions.

One downside is nesting can cause issues by compounding sizes, a problem known as specificity issues.

Rem

The rem (root em) works similarly to the em but is relative to the root html element's font-size:

html {
  font-size: 16px; 
}

p {
  font-size: 1rem; // 16px
} 

Rems avoid compounding size issues, so they are often easier to work with than ems.

Percentage (%)

Percentages are relative to the parent's size:

.parent {
  font-size: 12px;
}
  
.child {
  width: 50%; // 6px
}

Percentages are great for making fluid, responsive elements that scale up and down easily.

Viewport Units

Viewport units are relative to the viewport dimensions (browser window size). Two common viewport units are:

vw (Viewport width)

1vw equals 1% of the viewport width:

div {
  width: 50vw; // 50% of viewport width
}

vh (Viewport height)

1vh equals 1% of the viewport height:

img {
  height: 100vh; // 100% of viewport height
}

Viewport units create excellent responsive designs that fit any screen size. But avoid using them for small UI elements like text that become illegible if scaled.

Length Unit Conversions

To help understand relative lengths, here are some unit conversions:

  • 1in = 96px = 2.54cm
  • 1cm = 37.8px = 0.39in
  • 1em = 16px (by default browser font-size)
  • 1rem = 16px
  • 1vw = 1% of viewport width
  • 1vh = 1% of viewport height

Use online CSS unit converters when needed to translate units.

Angle Units

Now let's move on to angle CSS units - these define degrees of rotation or gradients:

Deg

Degrees are the most common angle unit:

.rotate {
  transform: rotate(45deg); 
}

Grad

Grads are based on a 400-grad circle rather than 360 degrees:

.skew {
  transform: skew(30grad);
}

Rad

The radian is the standard unit of angle measure used in math/physics:

.arc {
  stroke: arc(2rad); 
}

Turn

A turn equals a full 360 degree rotation:

.spin {
  transform: rotate(1turn);  
}

Deg and rad are the most useful options for web work. Grad and turn don't see as much use.

Time Units

CSS time units define durations and delays:

s

The s unit represents seconds:

.delay {
  transition-delay: 0.7s;
}

ms

The ms unit is milliseconds (1/1000 of a second):

.animate {
  animation: slide 2s;
}

@keyframes slide {
  0% { transform: translateX(0); }
  60% { transform: translateX(400px); }
  100% { transform: translateX(0); } 
}

This animates the slide effect over 2 seconds or 2000ms.

Frequency Units

For animation loops and iterations:

Hz

Hertz represents the number of occurrences per second:

.pulse {
  animation: pulse 5s infinite 2hz;
}

This pulses the animation 2 times per second.

kHz

Kilohertz equals 1000 Hertz:

.wiggle {
  animation: wiggle 100ms infinite 600hz;
}

Resolution Units

Resolution units define pixel density:

dpi

Dots per inch (dpi) defines dot density for print:

@media print {
  img {
    dpi: 300; // 300 dots per inch
  }
} 

Higher dpi images contain more fine detail.

dpcm

Dots per centimeter (dpcm) is the same concept as dpi but using centimeters:

div {
  border-image: url(border.png) 10 dpcm; 
}

dppx

Dots per pixel (dppx) defines pixel ratio for high resolution screens:

img {
  srcset: image.png 1x, 
         image-2x.png 2x,
         image-3x.png 3x;
} 

The 2x and 3x images display on 2x and 3x retina screens.

Fraction Units

The ch and rem units can also be used as fractions:

ch

The ch is relative to the 0 (zero) character width, allowing fluid line lengths:

p {
  width: 60ch; // 60x the width of 0
}

rem

Using rem fractions helps maintain vertical rhythm:

section {
  margin: 1.5rem 0; // 1

Spacing and Line Height Units

Ex

The ex unit is based on the height of lowercase x in the current font:

p {
  line-height: 1.5ex;
}

This sets the line-height to 1.5 times the x-height. Ex units allow consistent line spacing when font sizes change.

Ch

As we saw earlier, ch is the width of the 0 (zero) glyph. Ch units can create balanced typography:

p {
  max-width: 60ch;
}

This restricts paragraphs to 60 characters per line for better readability.

Lh

Line-height is the height of an entire line of text:

p {
  line-height: 1.2lh;
}

Setting line-height = lh scales the spacing based on changes to the font size.

Vw & Vh

Viewport width (vw) and height (vh) units also work for line lengths and spacing:

p {
  max-width: 70vw; // 70% of viewport width
}

section {
  margin: 5vh 0; // 5% of viewport height
}  

Calc()

The calc() function allows you to combine units and do math:

.box {
  width: calc(50% - 20px);
}

This subtracts 20px from 50% of the parent width.

Common Unit Use Cases

Now that we've explored all the main CSS units, let's summarize some best practices for when to use them:

  • Use px for fixed values like borders, padding, and precise UI elements
  • Use em or rem for font-sizes to allow reader scaling
  • Use % for fully responsive elements like widths and spacing
  • Use vh and vw for full-view responsive design
  • Use ex or ch units for better line lengths and spacing
  • Use s and ms units for animations and transitions

Avoid using...

  • cm, mm, in, pt, pc - mainly for print media
  • deg, grad, turn - rarely used in web design
  • Hz, kHz - occasionally for animation timing

By understanding when and why to reach for specific CSS units, you gain flexibility in crafting responsive, consistent designs. Always consider the needs of the user first when making decisions.

Conclusion

We covered a lot of ground explaining absolute and relative CSS units, angles, times, frequencies, resolutions, spacing, and more. The variety of options can seem overwhelming at first.

But start by mastering the most common units like px, em, rem, and % which you'll use every day. Learn when and why to use each one.

With more experience coding CSS, you'll gain intuition for which units make the most sense in different situations. The examples in this guide provide a solid starting point to build that understanding.

I hope these explanations and examples clarify CSS units and set you up for success using them in your web projects and designs! Let me know if you have any other questions.