CSS Custom Properties What are they, how can they be used and what are there key use cases? – By Eddy Haynes and Miri Jones

CSS custom properties, sometimes called variables or cascading variables contain specific values that allow coders to reuse them throughout the document. In this article, we discuss what they are, how they can be used with various methods, key use cases, uniqueness, and a summary of why they are worth including in your document.

What They Are

Custom Properties are variables within CSS (Cascading Style Sheets). They can be given any name and can store all of the styling information you normally declare within CSS, such as padding, font size, background colour etc. 

CSS custom properties “allow a value to be stored in one place, then referenced in multiple other places”, which is useful across “complex websites with lots of repeated values” (MDN Web Docs, 2023).

How To Use Them

The syntax of declaring a custom property adopts a similar style to declaring any property in a CSS file. You can put the custom property inside an individual element or on the root element property, which encompasses the whole HTML document, as will be described in more detail later in this article. 

To declare a custom property, you need to use a double ‘–’ dash before the name of your variable and then follow this with the styling information. *

Code from live demo(2023) https://codepen.io/TT48/pen/NWBZpLY

For example, a custom property used within our seminar demo was a small font with the unit of ‘2rem’ (this was declared in the root element more on this later).

This variable was then declared in the styling of the h3. Applying the styling in the h3 happens by first using the keyword var and then placing the CSS custom properties name inside the parameters (the brackets). Consequently, the unit of 2rem will be applied to the font size of the h3 element. The syntax of this example can be seen below.

Small font styling live demo (2023) https://codepen.io/TT48/pen/NWBZpLY

After creating this custom property, you can use it throughout the document.  Using the previous example from our demo ‘2rem’ was found to be an ideal font size for the paragraphs. To set them to that size was simply a case of declaring that same variable in the styling for the paragraph element.

Paragraph styling from live demo (2023) https://codepen.io/TT48/pen/NWBZpL

Along with the basic styling of the display block and text align left, you can see what the syntax for the styling for a custom variable looks like.

As can be seen, by this example, one of the inherent benefits of CSS custom properties is how it can integrate relatively seamlessly within the overall structure of the CSS file.

Naming The Variables

Naming the custom variables can be a difficult task in itself. It must be ensured that relevant names are chosen that make sense and relate to the value that will be declared. For example, if the colour ‘red’ is being declared for the background colour, then it would be logical to name the variable something like ‘–background-color’. This makes it easier if the CSS needs to be edited at a later date. It means the colour property can be changed without having to alter the name of the variable itself. However, if you named it something like ‘–background-red’ and it then proceeded to have the colour changed to purple, the variables name would no longer be relevant and it might also become confusing.

The importance of logically named variables becomes increasingly relevant when building a responsive website. One of the advantages of using CSS custom properties is that you can set various font, padding, and margin sizes, which can be used throughout your CSS file. Combining these stored properties with media queries enables you to build a responsive website design. 

Naming the different font sizes reflecting their purpose will help make the editing and development process more efficient. For example, we named the custom properties in our seminar demo, as shown below. 

Variable names from live demo (2023) https://codepen.io/TT48/pen/NWBZpL

Each variable is named based on its purpose. The naming of the fonts and padding reflect their unit size within the document. 

This simple naming of the custom properties was within the context of a short demo. However, if a more complicated website was being built. You could aim to be even more detailed and semantic with the naming of custom properties. For example, you could name the different font sizes based on the screen size they are useful for, so a variable that stores the font size of 1.5rem could be called –mobile-font. Whereas a variable with a larger font size could be called ‘–desktop-font’. You could even name font sizes suitable for certain phones or devices, i.e.‘–iphone-font’, ‘–small-android-font’ etc. 

Using a logical system with this level of consistency in naming variables allows anyone who needs to edit the styling information stored in the custom property to know the purpose of every variable, making building a responsive design a more systematic and rational process.

Methods of Use

Custom properties are most commonly used within the root of the HTML document itself. It is declared in the CSS file and written with a colon beforehand like this ‘:root’. An example of this could be:

:root { –h2-font-size: 5em; }

They can also be used within individual elements themselves. However, this is less common as it means the coder would still have to scroll through the CSS document to find the section where the values that need to be edited are located. For example, suppose your code was part of a commercial website. This could be a huge CSS file, so using the method of declaring within the root is always best practice in this circumstance.

header { –main-bg-color: brown; }

Why They’re Unique

While CSS- Preprocessors, such as SASS (Systematically Awesome Style Sheets) allow for variables, these variables are limited compared to CSS custom properties. They are not ‘dynamic’ (Hospodarets S, 2017), meaning they are fixed after being compiled and therefore cannot be changed. Preprocessor Files are ‘static’- when a SASS file with variables is compiled, “it will always lead to the same, fixed CSS values in the output file.” (Imms D, 2014).

The styling and the names of the  CSS custom properties can be changed on the fly during the “runtime” (Imms D, 2014). You can see a live example of this by editing the CSS directly within the DOM using a tool such as Firefoxes inspector. Using this tool you could change the colour of the styling information, i.e. changing a CSS-custom property called ‘–background-color’ from green to red and watch it immediately change within the browser. 

CSS custom properties follow the scope and rules of inheritance within the CSS cascade. For example, in our demo example we had set the custom property ‘–big-color’ in the root as shown below, 

Big color custom property from live demo https://codepen.io/TT48/pen/NWBZpLY

If we declared the same ‘–big-color’ CSS custom property in the body but changed the colour to blue, the heading elements, such as h1, would all change to blue rather than red. This is because the heading elements are a child of the body element. 

In our demo example, we had specific custom properties with different colours for h2 and h3, such as ‘–small-color’, ‘–medium-color’, but if we changed all the heading elements styling to ‘– big-color’, they would all change to blue. 

(Adapted from an explanation from Coyier C, 2016). 

The fact that CSS custom properties follow the cascade again allows for a lot of flexibility and makes the coding process semantic. 

Key Use Cases

Font Size 

Another key use case is using CSS custom properties to alter the font size on a website for different viewports. This can be done by declaring several variables within the ‘:root’ element that has a different scale for smaller or larger screens.  The example below shows that the variable named ‘scale1’ is the size for smaller screens, and the other variable named ‘scale2’ is the size for larger screens. The font size stays the same at 1em but is calculated with the particular scale size depending on if it is needed for smaller or larger screens. 

The font size (1em) gets multiplied by the variable, allowing it to continue scaling each time the breakpoint changes. In the media query, it has been stated that the min-width is 60em. This is in place to ensure that the font size doesn’t get too large and has a never-ending scaling size, as this wouldn’t look right on enormous screens.  Once the screen size reaches the point of 60em, the font size will stop scaling so that it still fits well with the overall layout of the web page.

Declaring these values in the documents root element makes it easy if any editing needs to be done in the future. It is most likely anything declared within the root would be placed at the top of the CSS document so automatically the coder knows exactly where to go to find the section to edit.

h5 using –scale1 custom variable
 
h5 using –scale2 custom variable and media query
CSS for the h5 example

Colour

Another key use case when CSS custom properties are beneficial is when using colour. The colour scheme is something that changes a lot at the beginning of a project. Commonly, coders and designers will try out different palettes on the website to see how they would match the design of the layout and the overall look of it. It is common to find a situation where two or three colours which in the swatches work well but, when seen together on a web page, do not work. For this reason, it is important to be able to test out ideas with the ability to alter them quickly if it is decided they need to be changed.

Creating variables for colour, such as for background colour, font colour, footer colour and so on and declaring them within the root element makes it easy to change the values. This saves a lot of time and effort, meaning the coder has less work to do, and the code becomes leaner, making it easier for others to read.

The example below shows how this can be implemented. It shows if there were one or two other elements, in this case the article element, that needed its properties to be a different value, this could easily be overwritten. Creating a new variable inside that element will ensure that what has been declared in the root will not affect this particular section of the web page.

Fortune Ikechi, LogRocket, 2021

If you follow the link below you can see our demo of how we used different custom properties with colour to create a design with different coloured headings.

If you follow the link below you can see our demo of how we used different custom properties with colour to create a design with different coloured headings. https://codepen.io/TT48/pen/NWBZpLY

Custom Colour themes – Advanced use case 

One method of starting to get even more creative with colours and CSS custom properties is to set colour themes. One of the most popular of these themes is a light and dark mode. 

The Odin Project (2023) has an excellent demo in which they allow users to toggle between a light and a dark mode. 

Root styling Odin Project 2023

As you can see from the Odin Project example above (2023), one means of achieving this is to put the light theme and the dark theme in separate classes in the root. These two classes in this example are called ‘.light’ and ‘.dark’. 

Once you have these two classes, you can then group all the styling of various elements under each class in semantically named CSS custom properties. In the dark mode class, we have properties such as ‘–color-base-b’ which stores the black background and ‘–border-btn’, which stores a grey border color for the button. The property names are the same in the ‘light’ class, but instead of the ‘–color–base-b’ storing a dark background, it stores a light background, and the ‘–border-btn’ property stores a dark shade for the border of the button to contrast with the light background.

End result 2023 Odin Project
End result 2023 Odin Project

As you can see from the example below, there are a number of different styling elements you can experiment with. The Odin Project (2023) demo even has different text appear depending on which theme is selected. 

The means of the user interacting with this can vary depending on the required complexity. However, it always requires a class to store the styling information and an event listener to wait for the user response to change the theme. The Odin Project (2023) uses a Javascript function and an event listener to call this function. For more information on the coding involved in the Odin Project (2023) demo visit here.

Layout Overall Structure and Fine Tuning

Custom properties, especially when semantically named, allow for flexibility while changing your layout both in terms of overall layout structure and fine-tuning your design. 

In terms of the overall layout and structure you could, for example, set a four colum grid in the root element, and then reuse this styling whenever you need it later on within your CSS file. It could be named ‘–num-of-col-4’, so you know its purpose. 

In comparison, you can also set the padding within variables in the root element for minor adjustments. For example, if you wanted to change the padding for headings and paragraphs, you could simply alter the units custom property on the root, i.e. reducing the size by 1rem. This change would then take place wherever you have declared the custom property for the padding in your CSS file. This is far more efficient than having to scan through your entire CSS file rechanging the value of the padding for each element.   

Padding styling from live demo(2023)

Looking at the example from our demo, editing any of these custom properties, will change the styling information of where we have used these elsewhere in the CSS file. 

Consequently, changing small padding to 1rem, will also change it in the paragraph element, which has its padding set to the ‘–small-padding’ custom property, as you can see from the example below.

Paragraph styling from live demo(2023)

Building Responsive Websites 

The flexibility of CSS custom variables in being referenced and called back to so efficiently is crucial to the development of responsive websites. When combined with media queries, this ability to set custom variables that affect the global layout and fine-tune individual elements makes CSS custom properties a valuable tool. This is especially true when these custom properties are semantically named. Looking at our demo earlier, we might decide we only want to bring in the small font padding variable for h3 at a certain screen width.

Resposive styling from live demo(2023)

Making slight adjustments is easy with CSS custom properties, as we have already seen so, you could easily create a slightly larger font, for a tablet screen size. We might even consider renaming our variables to ‘–mobile-font’,  ‘–mobile-padding’, and then ‘–tablet-padding’ and so on as explored earlier within this article.

This gives the user a huge amount of flexibility in adapting their style, even changing how they organise their system for styling depending on how many media queries are used and how complex the responsiveness of the website becomes. 

As demonstrated through the earlier example of using a calc method in CSS to set the specific scale for fonts, you can go even further than this in terms of advanced methods of CSS custom properties for responsive design.

CSS custom properties fit perfectly into a logical workflow, allowing the design to maintain consistency whilst efficiently making small adjustments and global changes to their design. This makes CSS custom properties increasingly vital to the overall responsive design process.

Browser Compatibility

CSS custom variables are largely supported throughout most modern browsers apart from Opera Mini and Internet Explorer where it is not supported at all. The var ( ) function can be used as “multiple fallback values when the given variable is not yet defined” (MDN Web Docs, 2023). If working with custom elements and shadow DOM (the shadow DOM allows hidden trees to be linked to elements in the regular DOM tree), then this can be a very useful thing to use. However, these fallback values do not work as a fallback for browser compatibility in case of situations where custom properties are not supported. In this case the standard CSS declarations would have to be used within each element, for example:

h2 { color: white; }

This ensures the web page will appear the same even if the custom properties fail. Whilst this does add to the amount of code within the document it ensures that everybody is included no matter what browser is being used. This can be judged accordingly. If the target audience of the website is on a smaller scale or only caters towards a specific demographic, where the developer knows that they use particular browsers that support custom properties, then it makes sense not to include the fallback as it would not be needed. 

Conclusion

In conclusion and as we described, CSS custom properties can be used effectively within the root of the document. They are a fantastic way to make code leaner and minimises effort, especially when collaborating with others.

Notes

*This is two single dashes separated by a space, as shown in the code snippets. WordPress renders this as one long dash, but the correct formatting is shown in the code screenshots.

Presentation Slides

Available https://www.canva.com/design/DAFZ5IJTe5Y/-tIVXVGWvKbNkjWeD4VRFg/edit?utm_content=DAFZ5IJTe5Y&utm_campaign=designshare&utm_medium=link2&utm_source=sharebutton

or as a PDF file

Live Code Demo Available https://codepen.io/TT48/pen/NWBZpLY

References

Coyier Chris, October 25th 2016. Accessed 18th of Feb 2023. https://css-tricks.com/difference-between-types-of-css-variables/ 

Ikechi Fortune, Log Rocket Front End Analysis, May 10, 2021. Accessed 17th of Feb 2023.

https://blog.logrocket.com/css-custom-properties-as-of-2021/

Imms Daniel, Sitepoint, 26th Aug 2014. Accessed 17th Feb 2023.

What CSS Variables Can Do That Preprocessors Can’t — SitePoint 

MDN Web Docs, 2023. Accessed 17th Feb 2023. https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties 

Odin Project, 2023. Accessed 17th of Feb 2023.

https://www.theodinproject.com/lessons/node-path-intermediate-html-and-css-custom-properties

Serg Hospodarets, Smashing Magazine, April 19th, 2017. Accessed 17th Feb 2023.

It’s Time To Start Using CSS Custom Properties — Smashing Magazine

Useful Links

https://caniuse.com/?search=css%20custom%20properties

https://12daysofweb.dev/2021/css-custom-properties/

https://blog.webdevsimplified.com/2020-02/css-custom-properties/

https://blog.logrocket.com/css-custom-properties-as-of-2021/

Leave a Reply

Your email address will not be published. Required fields are marked *