I enjoy using css custom properties, but there's this thing that I often find that I wish I could do.
I wish to be able to apply some styles conditionally based on the value of a css custom property. Here's some pseudo-code:
.something {
border: var(--is-dark-theme) ? 1px solid : none;
}
I understand that custom properties do not work like this. But may be there is some other way that I'm not aware of that could help me achieve a similar result?
Or perhaps there is some spec proposal that would this possible in the future?
The @property “at-rule” in CSS allows you to declare the type of a custom property, as well its as initial value and whether it inherits or not.
No, We can not use if-else conditions in CSS as CSS doesn't support logics. But we can use some alternatives to if-else which are discussed below: Method 1: In this method, we will use classes in HTML file to achieve this. We will define different class names according to the conditions which we want to apply in CSS.
Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document.
var() The var() CSS function can be used to insert the value of a custom property (sometimes called a "CSS variable") instead of any part of a value of another property.
Here is another idea similar to Ori Drori answer where I rely on the use of an invalid value inside border to remove the border. This can be useful in case you want to use keywords like false
/true
/yes
/no
.something {
border: var(--is-dark-theme,2px) solid black;
}
<div class="something">Dark theme</div>
<div class="something" style="--is-dark-theme: false">Light theme</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With