CSS already has had conditionals in the form of @media queries or @support queries to selectively apply styling to the document. But there is a new proposal called when/else which takes it to a different level.
Let us take a look at how they work.
Using media queries
Using media queries, if we were to make our page responsive, we could add some logic like
And if we wanted to add some logic for smaller resolutions, we would do
The when else syntax is cleaner:
And it even supports multiple conditionals
Creating generalized rules
When else is not limited to @media queries. It can be combined with other conditionals as well.
So instead of doing:
We can simply do:
@when can also be used inline
When the width is less than 400 pixels, the padding would be 1 rem instead of 2 rem.
Additional new ways of writing media queries
There is another proposal to the media queries spec, which will allow more semantic conditions while writing media queries themselves. It is again a level 4 specification right now.
Instead of writing min-width and max-width, media queries could then be rewritten as
The proposals are moving along fairly quickly and CSS has been on a tear lately. There is a debate about using @if instead of @when but the argument is that it’d conflict with Sass. There is a proposal to replace it with @where as well.
Irrespective of the name, this will be a great addition to the CSS toolset.