Tip 032 - Logic Gate in CSS
Here are a few random CSS facts:
- You can use the
calc()function to perform mathematics with different numbers and length values.
- CSS is error-resilient - if a line is off, the browser will ignore the one line and continue on.
- Length values might be invalid if they are a negative number
Get ready for a wild ride today.
Lets say you really wished CSS was more programmatic, and had something like an if/then statement. Depending on the property you're looking to set and how clever you are about it, you can absolutely do that.
First off, you can test your condition with a
calc() run, usually something like
400px - 100%. This will result in either a positive or a negative number, depending on the context of the element. In most cases a negative length is not allowed, and is therefore ignored. A positive value is used normally. Congratulations, you now have some rudimentary logic!
What's a use case for this? Here, this is used to automatically determine an accessible text color based on the background color. And here, it's used to help a flexbox layout go straight from three columns to one without
all that tedious mucking about in hyperspace passing through a two-column layout in the middle.