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?
Not in the traditional sense, but you can use classes for this, if you have access to the HTML. Consider this:
and in your CSS file:
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:
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:
Finally, you can preprocess your stylesheet with your favourite server-side language. If you’re using PHP, serve a
style.css.phpfile, that looks something like this:In this case, you will however have a performance impact, since caching such a stylesheet will be difficult.
On a more high-level note, Ahmad Shadeed shows in this article a lot of very useful techniques to decide if/else questions often coming up in UI development purely within CSS.