Categories: css-tricks.com

Proposal for CSS @when

CSS is on a tear lately. Again, I’ve heard of a brand new thing I’ve never seen before, and again it’s via Miriam: CSS Conditionals.

There is already such a thing as logic in media queries. In fact, a media query is already logic.

@media (min-width: 600px) {
  /* WHEN this media query is true, do these styles. */}

And if you want to have styles that are mutually exclusive to the above, you’d write two media queries:

@media (min-width: 600px) {
  /* ... */ 
}
@media (max-width: 599px) {
  /* ... */}

That’s a little… fidgety. The syntax is much cleaner in this new proposal:

@when media(min-width: 600px) {
  /* ... */ 
}
@else {
  /* ... */ 
}

Looks like you can do multiple conditions via and, have a waterfall logic stack with multiple @else statements, and not just use @media, but @supports as well.

@when media(width >= 400px) and media(pointer: fine) and supports(display: flex) {
  /* A */} @else supports(caret-color: pink) and supports(background: double-rainbow()) {
  /* B */} @else {
  /* C */}

Looks very logical and handy to me!

I saw one little squabble about the naming. @if could be a logical name here too. But Sass uses @if and it would be super annoying to a ton of developers if they had to refactor all their Sass logic to something new or however that would fall out. Should CSS cede to any preprocessor out there? Nah, but Sass has been around a long time and is super popular, and there is a perfectly good alternative, so why cause the pain? In that thread, it’s not just about Sass either — some folks think @when is a better name anyway.


The post Proposal for CSS @when appeared first on CSS-Tricks. You can support CSS-Tricks by being an MVP Supporter.

hnikoloski

Share
Published by
hnikoloski

Recent Posts

Demystifying Screen Readers: Accessible Forms & Best Practices

This is the 3rd post in a small series we are doing on form accessibility.…

3 weeks ago

Managing User Focus with :focus-visible

This is going to be the 2nd post in a small series we are doing…

1 month ago

The Power of :has() in CSS

Hey all you wonderful developers out there! In this post we are going to explore…

1 month ago

Accessible Forms with Pseudo Classes

Hey all you wonderful developers out there! In this post, I am going to take…

2 months ago

Passkeys: What the Heck and Why?

These things called passkeys sure are making the rounds these days. They were a main attraction at W3C…

1 year ago

Some Cross-Browser DevTools Features You Might Not Know

I spend a lot of time in DevTools, and I’m sure you do too. Sometimes…

1 year ago