In CSS on

Modern CSS Techniques

Practical tips on building UI with modern CSS techniques

New CSS features drop constantly, and it’s easy to fall behind. I was guilty of this myself, I kept avoiding things I assumed weren’t supported yet, only to realize years later they’d been in modern browsers the whole time. Here are a few I’ve finally started using.

Sizing icons with the lh unit

Sizing an inline icon relative to the surrounding text has traditionally been awkward, you’d either hard-code a pixel value that breaks when font size changes, or use 1em which doesn’t account for line height. The lh unit solves this cleanly. In the demo below, resize the text and notice how the icon scale proportionally.

.icon {
  width: .8lh;
  height: .8lh;
}
Like
Font Size20px

Centering with CSS Grid

Say you have an image with a magnifying glass icon centered over it to hint that it opens a lightbox. Here’s how I used to handle that.

.image-wrapper {
  position: relative;
}
.icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

5 lines of CSS to center a div. With CSS Grid, it only takes two. Just use display: grid and place-content: center.