@when – CSS-Tricks https://css-tricks.com Tips, Tricks, and Techniques on using Cascading Style Sheets. Mon, 27 Dec 2021 14:12:56 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://i0.wp.com/css-tricks.com/wp-content/uploads/2021/07/star.png?fit=32%2C32&ssl=1 @when – CSS-Tricks https://css-tricks.com 32 32 45537868 Proposal for CSS @when https://css-tricks.com/proposal-for-css-when/ https://css-tricks.com/proposal-for-css-when/#comments Tue, 21 Sep 2021 22:54:51 +0000 https://css-tricks.com/?p=352328 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.


Proposal for CSS @when originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
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.


Proposal for CSS @when originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

]]>
https://css-tricks.com/proposal-for-css-when/feed/ 12 352328