Can You Use If/else Conditions In CSS?


Answer :

Not in the traditional sense, but you can use classes for this, if you have access to the HTML. Consider this:

<p class="normal">Text</p>  <p class="active">Text</p> 

and in your CSS file:

p.normal {   background-position : 150px 8px; } p.active {   background-position : 4px 8px; } 

That's the CSS way to do it.


Then there are CSS preprocessors like Sass. You can use conditionals there, which'd look like this:

$type: monster; p {   @if $type == ocean {     color: blue;   } @else if $type == matador {     color: red;   } @else if $type == monster {     color: green;   } @else {     color: black;   } } 

Disadvantages are, that you're bound to pre-process your stylesheets, and that the condition is evaluated at compile time, not run time.


A newer feature of CSS proper are custom properties (a.k.a. CSS variables). They are evaluated at run time (in browsers supporting them).

With them you could do something along the line:

:root {   --main-bg-color: brown; }  .one {   background-color: var(--main-bg-color); }  .two {   background-color: black; } 

Finally, you can preprocess your stylesheet with your favourite server-side language. If you're using PHP, serve a style.css.php file, that looks something like this:

p {   background-position: <?php echo (@$_GET['foo'] == 'bar')? "150" : "4"; ?>px 8px; } 

In this case, you will however have a performance impact, since caching such a stylesheet will be difficult.


Below is my old answer which is still valid but I have a more opinionated approach today:

One of the reasons why CSS sucks so much is exactly that it doesn't have conditional syntax. CSS is per se completely unusable in the modern web stack. Use SASS for just a little while and you'll know why I say that. SASS has conditional syntax... and a LOT of other advantages over primitive CSS too.


Old answer (still valid):

It cannot be done in CSS in general!

You have the browser conditionals like:

/*[if IE]*/  body {height:100%;}  /*[endif]*/ 

But nobody keeps you from using Javascript to alter the DOM or assigning classes dynamically or even concatenating styles in your respective programming language.

I sometimes send css classes as strings to the view and echo them into the code like that (php):

<div id="myid" class="<?php echo $this->cssClass; ?>">content</div> 

You can use calc() in combination with var() to sort of mimic conditionals:

:root { --var-eq-two: 0; }  .var-eq-two {     --var-eq-two: 1; }  .block {     background-position: calc(         150px * var(--var-eq-two) +         4px * (1 - var(--var-eq-two))     ) 8px; } 

concept


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?