CSS offers several powerful programming language-type features, such as the var() and calc() functions for variables.

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:

  1. W3Schools.com (no date) CSS Variables – The var() function. Available at: https://www.w3schools.com/css/css3_variables.asp (Accessed: 2 June 2025).
  2. W3Schools.com (no date) W3Schools Online Web Tutorials. Available at: https://www.w3schools.com/cssref/sel_root.php (Accessed: 12 June 2025).
  3. W3Schools.com. (no date) CSS calc() Function. Available at: https://www.w3schools.com/cssref/func_calc.php (Accessed: 24 August 2025)

By @MisterFoxOnline

Mister Fox AKA @MisterFoxOnline is an ICT, IT and CAT Teacher and Young Engineers instructor. He has a passion for technology and loves to find solutions to problems using the skills he has learned in the course of his IT career.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.