CSS Is Finally Getting If/Else Statements!

Kenton de Jong on 2021-10-09

When I started coding CSS in 2011 (wow) I could never have suspected how much the language would change. I still remember using PIE.htc to make border-radius work across all browsers, and my coworker making a PHP script that generated a PNG to round corners.

How far we have come!

You got that right, sister.

However, the past few years have rolled out an explosive amount of new CSS features. Some of these could be perceived as “if statements” too, like the @supports style:

@supports (border-radius: 50%) {
   //don't use PIE.htc! {}
}

(Do you think my CSS comment is a typeo? It’s not. CSS does have single-line comments. They’re just a little weird.)

There is also the classic media query too, which has been around for over a decade:

@media (max-width: 1000px) {
  //maybe a mobile sized device? {}
}

There’s also the new clamp() which is a little different, but looks like this:

width: clamp(1000px, 50%, 10vw);

But acts like this:

width: clamp(1000px >= (50% >= 10vw));
That’s right kid, and clamp() makes my head hurt sometimes too.

But those are arguable just “if statements”. If we wanted an “if/else statement” we would need to do something like this:

@media (max-width: 1000px) and (prefers-color-scheme: dark) {
   //maybe a mobile device in dark mode {}
}
@media (max-width: 1000px) and (prefers-color-scheme: light) {
   //maybe a mobile device in light mode {}
}

Which is annoying.

But thankfully we can be annoyed no more with the newly proposed @when statement. It works something like this:

@when media(max-width: 1000px) {
   //maybe a mobile device {}
}

Which is cool, I guess. But what about an else?

@when media(max-width: 1000px) {
   //maybe a mobile device {}
} @else {
   ///maybe…