Using CSS Variables / Custom Properties – HTML & CSS – SitePoint Forums

I did some research before this post.

I’m struggling to understand css variables/custom properties… how they work and how they are beneficial and when I should use them

I would appreciate some (substantial) explanations

and some novice examples

go easy for me

I’m new to this concept

Thank you!


I use quite a few CSS variables, and looking at a website it looks like I’m using them for two purposes. There are probably other good reasons to use them, but I’m just telling you that’s what I use them for.

  1. I hate “magic numbers”, whether they’re buried in my CSS, JS, or PHP. So I’m trying to pull them from everywhere else and put them as CSS variables (and in PHP as PHP constants). So, for example, I have a good number that looks like:
--body-top-border:15px;	/* Top margin size of dark border (goes away as browser shrinks) */
--button-color:#DDD;	/* Color for all tab and button links */
--box-padding:3px;		/* Padding for any text box */

This type of variable is used in my CSS, like:

body {margin-top:var(--body-top-border)}
article {padding:var(--box-padding);color:var(--text-color)}

where for the body element, I really didn’t save anything, but I extracted the magic “15px” value that would otherwise be buried in my CSS, and put it in the CSS variable block. For the article padding I used it in many places so all my boxes have the same padding and I just declare the 3px value once. There are of course other ways to do this, with a class like “.thinPadding” that could be added to each of my boxes, but I find the CSS variable quite handy for this. Also, if I’m looking at my site and decide the padding needs to be a little thicker, I can just access the CSS variable and edit it in one place.

  1. The second use of CSS variables is for calculated values ​​that can be turned into a single variable, to make my life easier. I don’t use it as much as the first use, but as an example:
--default-box-content:calc(var(--box-size) - 2 * var(--box-padding));

This would allow me to set another CSS value like this, without having to remember the details of what that box looks like:

#messageContent {width:var(--default-box-content)}

I hope these examples help you.



2 likes

They are commonly used to set up a default theme (or themes) in your project where you can set all site colors as variables in the :root at the start of the css. Then when you want to change a color sitewide, you only need to update one CSS variable and not thousands of sitewide rules. You can do the same for fonts etc. and perhaps the default padding margins, if any.

Look at the CSS in any frame and you will see how they have configured their custom CSS properties.

James S. Joseph