A few trix with modern CSS

This week, I'm diving deep into the help we can get from the new CSS features we've gained in recent years. I mean, who doesn't want assistance in optimizing our code?

I could write a really long article about this, and maybe I will. But for now, I just want to give you a few trix of how CSS nesting, CSS variables and media queries can lend us a hand in our daily work. Tag along!

.grid {
  display: grid;
  gap: 16px;
  grid-template-columns: repeat(4, 1fr);
}

@media (max-width: 700px) {
  .grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 375px) {
  .grid {
    grid-template-columns: 1fr;
  }
}

Check out this example of an old way of writing our code. We actually add the selector ‘grid-template-columns’ three times. And, I don’t know about you, but the min-width media query has always puzzled me. So the question is, is there a better way in terms of readability and reducing redundancy? I would say there is.

.grid {
  display: grid;
  grid-template-columns: repeat(var(--n, 4), 1fr);
  gap: 16px;

  @media (width < 700px) {
    --n: 2;
  }

  @media (width < 375px) {
    --n: 1;
  }
}

You see, with CSS nesting, we can use one selector instead of three. We’re also able to assign a value to just one property and then changing it according to different conditions. And when you look at the media query, you can figure it out in a second without even having to think about it.

The code has the same purpose and will be handled by the browser in the same way. However it’s easier to maintain, has fewer steps and more readability.

Pretty neat, don’t you think?