Can you use if/else conditions in CSS?
I am surprised that nobody has mentioned CSS pseudo-classes, which are also a sort-of conditionals in CSS. You can do some pretty advanced things with this, without a single line of JavaScript.
Some pseudo-classes:
- :active - Is the element being clicked?
- :checked - Is the radio/checkbox/option checked? (This allows for conditional styling through the use of a checkbox!)
- :empty - Is the element empty?
- :fullscreen - Is the document in full-screen mode?
- :focus - Does the element have keyboard focus?
- :focus-within - Does the element, or any of its children, have keyboard focus?
- :has([selector]) - Does the element contain a child that matches [selector]? (Sadly, not supported by any of the major browsers.)
- :hover - Does the mouse hover over this element?
- :in-range/:out-of-range - Is the input value between/outside min and max limits?
- :invalid/:valid - Does the form element have invalid/valid contents?
- :link - Is this an unvisited link?
- :not() - Invert the selector.
- :target - Is this element the target of the URL fragment?
- :visited - Has the user visited this link before?
Example:
div { color: white; background: red }
input:checked + div { background: green }
<input type=checkbox>Click me!
<div>Red or green?</div>
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.