{"id":292074,"date":"2019-09-11T07:26:02","date_gmt":"2019-09-11T14:26:02","guid":{"rendered":"http:\/\/css-tricks.com\/?p=292074"},"modified":"2019-10-04T07:44:50","modified_gmt":"2019-10-04T14:44:50","slug":"logical-operations-with-css-variables","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/logical-operations-with-css-variables\/","title":{"rendered":"Logical Operations with CSS Variables"},"content":{"rendered":"

Very often, while using switch variables (a variable that’s either 0<\/code> or 1<\/code>, a concept that’s explained in a greater detail in in this post<\/a>), I wish I could perform logical operations on them. We don’t have functions like not(var(--i))<\/code> or and(var(--i), var(--k))<\/code> in CSS, but we can emulate these and more with arithmetic operations in a calc()<\/code> function.<\/p>\n

This article is going to show you what calc()<\/code> formulas we need to use for each logical operation and explain how and why they are used with a couple of use cases that lead to the writing of this article.<\/p>\n

How: the formulas<\/h3>\n

not<\/code><\/h4>\n

This is a pretty straightforward one: we subtract the switch variable (let’s call it --j<\/code>) from 1<\/code>:<\/p>\n

--notj: calc(1 - var(--j))<\/code><\/pre>\n

If --j<\/code> is 0<\/code>, then --notj<\/code> is 1<\/code> (1 - 0<\/code>). If j<\/code> is 1<\/code>, then --notj<\/code> is 0<\/code> (1 - 1<\/code>).<\/p>\n

and<\/code><\/h4>\n

Now, if you’ve ever taken electronics classes (particularly something like Programmed Logic Systems or Integrated Circuits), then you already know what formula we need to use here. But let’s not jump straight into it.<\/p>\n

The and<\/code> of two operands is true if and only if both are true. The two operands in our case are two switch variables (let’s call them --k<\/code> and --i<\/code>). Each of them can be either 0<\/code> or 1<\/code>, independently of the other. This means we can be in one out of four possible scenarios:<\/p>\n