if/else in CSS

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:

We can use CSS preprocessors like SASS which allows us to write condition statements in it. Even if you use SASS you have to pre-process your stylesheets which means that the condition are evaluated at compile time, not at run time.

SASS Syntax:

The above work well, but in the new proposal it looks much cleaner and very similar to many programming languages.

Here is the new proposed syntax

We can do multiple conditions as well by using multiple @else statements, and not just use @media, but @supports too.

Naming this new feature is still not clear. I think that @if would be a better name than @when. However the reason behind this naming is probably that Sass already uses @if, and it would be very annoying to many developers if they had to refactor their Sass code.

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?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: