CSS Math

By Tony 8.29.2024


Imagine a situation where a lot of the elements on your page use the same background color, but it's only for the dark mode of the page, and you need to set a new background color for each element again if the user activates the light mode. How can you achieve this with minumum code? That's where CSS variables come in. In this tutorial, we'll teach you the basics of CSS math functions and variables.

width: calc(50vw - 100px);
background-color: var(--bg-color);

Maybe you've already noticed the weird calc and var values with parenthesis. These are called CSS value functions. The calc() value function involkes, or runs, a built-in CSS function that does math calculations with CSS values. In this example, the calc() function sets the element's width to the difference of 50vw and 100px. Why do we want to use the math function when we can just set a simple, say, 50px width to an element? It's for flexibility. You may want to create elements that adapt to different screen sizes by having values with different units combined so the elements look great on any device. As of the other value function, var(), it's basically just a placeholder for the value of the property. In this example, it replaces the actual value of the background-color property with the --bg-color variable. This is very useful when you want to have the same value applied to many different elements. With CSS variables, you don't have to reset the values one by one when you want to change them, instead, you can just change one variable, and the change is applied to all the elements with that variable. Note that you have to set the variable first in the :root selector (see example below), and the variable name must always begin with 2 dashes --.

HTML
CSS
JavaScript
Output

In conclusion, calc() and var() are both CSS value functions that are powerful features in CSS. calc() uses math to calculate the value of 2 values with different units combined. The var() function returns the variable's value. It's very useful when you want to dynamically change a CSS value across multiple elements without changing them one by one.