CSS offers several powerful programming language-type features, such as the var() and calc() functions for variables.
In this tutorial:
Required knowledge:
var() Syntax
Declare the variable and assign a value:
:root {
--nameofvariable: valueforvariable;
}
Use the variable:
selector {
attribute: var(--nameofvariable);
}
Naming variables (and functions, etc.) is a skill. Naming your CSS variable deepred seems intuitive, until “someone” decides that burnt orange would be a better colour, and all of a sudden your CSS makes no sense! I am a fan of verbose naming, so my code is littered with long variable names like keylogocolour and secondarylogocolour.
:root refers to the document’s root element. In HTML, the root element always refers to the <html> element.
Example
One useful scenario is to variableise your colours in your CSS. Admittedly, in this example, we are using them more as constants than variables.
:root {
--logoblue: #1e90ff;
--logogrey: #c3c3c3
--logobgcolor: #F5F5F5;
}
body {
background-color: var(--logobgcolor);
}
You can assign new values to your variables later in the “cascade”, which adds to their usefulness.
calc() Syntax
This is an extract of some responsive code I wrote, where I defined a variable for the border width of divs and a calculation to define the width for smaller devices:
:root {
--borderthick: 0.7vw;
}
body>div+div {
border: var(--borderthick) solid var(--scratchorange);
}
@media (max-width: 800px) {
body>div+div {
border-width: calc(var(--borderthick)*2);
}
}
References:
- W3Schools.com (no date) CSS Variables – The var() function. Available at: https://www.w3schools.com/css/css3_variables.asp (Accessed: 2 June 2025).
- W3Schools.com (no date) W3Schools Online Web Tutorials. Available at: https://www.w3schools.com/cssref/sel_root.php (Accessed: 12 June 2025).
- W3Schools.com. (no date) CSS calc() Function. Available at: https://www.w3schools.com/cssref/func_calc.php (Accessed: 24 August 2025)