Question

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;
[else]
    background-position : 4px 8px; 

Can this be done? How do you do this?

Was it helpful?

Solution

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.

OTHER TIPS

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 could create two separate stylesheets and include one of them based on the comparison result

In one of the you can put

background-position : 150px 8px;

In the other one

background-position : 4px 8px;

I think that the only check you can perform in CSS is browser recognition:

Conditional-CSS

Set the server up to parse css files as PHP and then define the variable variable with a simple PHP statement.

Of course this assumes you are using PHP...

You can use not instead of if like

.Container *:not(a)
{
    color: #fff;
}

This is a little extra info to the Boldewyn answer above.

Add some php code to do the if/else

if($x==1){
  print "<p class=\"normal\">Text</p>\n";
} else {
  print "<p class=\"active\">Text</p>\n";
}

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

As far as i know, there is no if/then/else in css. Alternatively, you can use javascript function to alter the background-position property of an element.

Yet another option (based on whether you want that if statement to be dynamically evaluated or not) is to use the C preprocessor, as described here.

(Yes, old thread. But it turned up on top of a Google-search so others might be interested as well)

I guess the if/else-logic could be done with javascript, which in turn can dynamically load/unload stylesheets. I haven't tested this across browsers etc. but it should work. This will get you started:

http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

You can add container div for all your condition scope.

Add the condition value as a class to the container div. (you can set it by server side programming - php/asp...)

<!--container div-->
<div class="true-value">
   <!-- your content -->
   <p>my content</p>
   <p>my content</p>
   <p>my content</p>
</div>

Now you can use the container class as global variable for all elements in the div using nested selector, without adding the class to each element.

.true-value p{
   backgrounf-color:green;
}
.false-value p{
   backgrounf-color:red;
}

CSS is a nicely designed paradigm, and many of it's features are not much used.

If by a condition and variable you mean a mechanism to distribute a change of some value to the whole document, or under a scope of some element, then this is how to do it:

var myVar = 4;
document.body.className = (myVar == 5 ? "active" : "normal");
body.active .menuItem {
  background-position : 150px 8px;
  background-color: black;
}
body.normal .menuItem {
  background-position : 4px 8px; 
  background-color: green;
}
<body>
<div class="menuItem"></div>
</body>

This way, you distribute the impact of the variable throughout the CSS styles. This is similar to what @amichai and @SeReGa propose, but more versatile.

Another such trick is to distribute the ID of some active item throughout the document, e.g. again when highlighting a menu: (Freemarker syntax used)

var chosenCategory = 15;
document.body.className = "category" + chosenCategory;
<#list categories as cat >
    body.category${cat.id} .menuItem { font-weight: bold; }
</#list>
<body>
<div class="menuItem"></div>
</body>

Sure,this is only practical with a limited set of items, like categories or states, and not unlimited sets like e-shop goods, otherwise the generated CSS would be too big. But it is especially convenient when generating static offline documents.

One more trick to do "conditions" with CSS in combination with the generating platform is this:

.myList {
   /* Default list formatting */
}
.myList.count0 {
   /* Hide the list when there is no item. */
   display: none;
}
.myList.count1 {
   /* Special treatment if there is just 1 item */
   color: gray;
}
<ul class="myList count${items.size()}">
<!-- Iterate list's items here -->
<li>Something...</div>
</ul>

If you're open to using jquery, you can set conditional statements using javascript within the html:

$('.class').css("color",((Variable > 0) ? "#009933":"#000"));

This will change the text color of .class to green if the value of Variable is greater than 0.

You can use javascript for this purpose, this way:

  1. first you set the CSS for the 'normal' class and for the 'active' class
  2. then you give to your element the id 'MyElement'
  3. and now you make your condition in JavaScript, something like the example below... (you can run it, change the value of myVar to 5 and you will see how it works)

var myVar = 4;

if(myVar == 5){
  document.getElementById("MyElement").className = "active";
}
else{
  document.getElementById("MyElement").className = "normal";
}
.active{
  background-position : 150px 8px;
  background-color: black;
}
.normal{
  background-position : 4px 8px; 
  background-color: green;
}
div{
  width: 100px;
  height: 100px;
  }
<div id="MyElement">
  
  </div>

You can use php if you write css in the Tag

<style>
    section {
        position: fixed;
        top: <?php if ($test == $tset) { echo '10px' }; ?>;
    }
</style
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top