Haim Evgi Haim Evgi - 3 months ago 5
CSS Question

Can you use if/else conditions in CSS?

I would like to use conditions in my CSS.

The idea is that I have a variable that I replace when the site is run to generate the right style-sheet.

I want it so that according to this variable the style-sheet changes!

It looks like:

[if {var} eq 2 ]
background-position : 150px 8px;
background-position : 4px 8px;

Can this be done? How do you do this?



No, 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.

Also, there are CSS preprocessors like Less, but little of them have support for conditional statements, and you have the hassle to run your stylesheets through their processors.

Alternatively, 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.