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.

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 icons scale proportionally.

Pengu 1Pengu 2
Pudgy Penguins
Font Size26px
Icon Size

Centering with CSS Grid

Centering an element with CSS grid is really easy. All you need is to set the parent to display: grid and place-content: center. The place-content is actually a shorthand for justify-content and align-items. Isn’t it awesome that we only need 2 lines to center a div now.

.images-wrapper {
  display: grid;
  place-content: center;
}
Cat 1

We can take this a step further. We can actually center multiple elements inside of a container in the same place without using position: absolute. I learned this neat trick from Josh Comeau, you can check his full tutorial here.

.images-wrapper {
  display: grid;
  place-content: center;
  place-items: center; 
}

img {
  grid-row: 1;
  grid-column: 1;
}

img:last-child {
  rotate: 12deg;
}
Cat 1Cat 2

Animatable CSS variables with @property

The best use case for @property is to define an animatable CSS variable. Let’s say we have a We then can use this animatable CSS variable and put it inside a CSS property that is not animatable.

For example, we can put this new property to animate gradients. Scroll over to the ball to see the gradient animation.

@property --color-1 {
  syntax: "<color>";
  inherits: false;
  initial-value: purple;
}

@property --color-2 {
  syntax: "<color>";
  inherits: false;
  initial-value: pink;
}

/* this allows the custom property to be animatable */
.ball {
  transition: --color-1 .3s ease, --color-2 .3s ease;
}
	
.ball:hover, .ball:active {
  --color-1: indigo;
  --color-2: aqua;
}

Isn’t that easy? The old would’ve required us to have a pseudo element for the second gradient layer. Now we can just use @property to do this.