CSS has come a long (long) way since I first got into the web dev space. One neat feature that has me excited is the ability to (finally) use CSS Custom Properties (CSS Props) in more modern browsers.
The gist is that CSS Props are a way to define variables in CSS that can be used in a variety of ways, similar to how you might use variables in PHP, JavaScript, Python, etc.
In a lot of places and scenarios! For instance, you can use CSS Props to manage your layout dimensions and color values, for instance, but you can also use them to create design systems, either for your own projects or for a team.
Check this. I'm going to define a CSS Prop called --my-awesome-prop and set it to 1rem:
:root { --my-awesome-prop: 1rem; }
Now, I can use that variable in any other CSS selector:
.my-awesome-class { font-size: var(--my-awesome-prop); }
So, what's going on here? Well, the :root selector is a special selector that refers to the root element of the document. In other words, it's the <html> element. So, when I define a CSS Prop on the :root selector, I'm defining it on the <html> element.
Then, I can use that variable in any other CSS selector. In this case, I'm using it in the .my-awesome-class selector. The var() function is used to reference a CSS Prop. So, in this case, I'm referencing the --my-awesome-prop variable.
Tip: You don't have to use the :root pseudo selector to define all of
your CSS Props. Check out this example
from Una where they leverage an element's scope for their CSS Props.
CSS Props are gaining support in all modern browsers. As usual, IE11 likes to throw us a curve ball, in this case, IE11 doesn't support the var() function, so we'll need to use a fallback value. For example:
.my-awesome-class { font-size: var(--my-awesome-prop, 1rem); }
For the latest browser support, check out Can I Use.
You can also use CSS Props in JavaScript. For example, you can use them to set the value of a CSS variable on an element:
const myAwesomeElement = document.querySelector('.my-awesome-class'); myAwesomeElement.style.setProperty('--my-awesome-prop', '1rem');
You can also use them to get the value of a CSS variable on an element:
const myAwesomeElement = document.querySelector('.my-awesome-class'); const myAwesomeProp = myAwesomeElement.style.getPropertyValue('--my-awesome-prop');
Pretty neat, right? I'm excited to see what we can do with CSS Props in the future. I'm sure we'll see some cool stuff from the community.
Related: