This content originally appeared on DEV Community and was authored by Damian Brdej
As we know, there are no conditional statements in CSS, but this may soon change with new @when
and @else
operator
Currently, the only way to perform a conditional statement was to use media queries like this:
@media (min-width: 600px) {
/* ... */
}
@media (max-width: 599px) {
/* ... */
}
It works perfectly, but in the new proposal it looks much cleaner and very similar to many programming languages.
@when media(min-width: 600px) {
/* ... */
}
@else {
/* ... */
}
We can do multiple conditions as well by using multiple @else
statements, and not just use @media, but @supports too.
@when media(width >= 600px) and media(pointer: fine) and supports(display: grid) {
/* A */
} @else supports(caret-color: red) and supports(background: double-rainbow()) {
/* B */
} @else {
/* C */
}
There may be questions about the naming of this new feature. Some people think that @if
would be a better name than @when
, the reason behind this naming is probably that Sass already uses @if
, and it would be annoying to many developers if they had to refactor their Sass logic.
The bad news is that it's not supported by any browser at this moment, it's not even listed on caniuse.com
.
What do you think about this new proposal?
This content originally appeared on DEV Community and was authored by Damian Brdej
Damian Brdej | Sciencx (2021-12-25T22:53:31+00:00) if/else in CSS. Retrieved from https://www.scien.cx/2021/12/25/if-else-in-css/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.