Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional styles with css custom properties

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?

like image 787
timetowonder Avatar asked Oct 02 '18 21:10

timetowonder


People also ask

How will you declare a custom property in CSS?

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.

Can we add condition in CSS?

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.

What do CSS custom properties variables mean?

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.

Can I use var CSS?

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.


1 Answers

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>
like image 177
Temani Afif Avatar answered Sep 20 '22 03:09

Temani Afif