If you have any questions or feedback, pleasefill out this form
This post is translated by ChatGPT and originally written in Mandarin, so there may be some inaccuracies or mistakes.
I previously wrote an article sharing my thoughts on CSS variables. Initially, I didn't have high expectations for this feature, as I was accustomed to using SASS variables, and found CSS variables to be somewhat cumbersome. However, if you feel the same way, you might want to check out this article Why should you care about CSS variables.
CSS variables have been around for a while now, and browser support isn't too shabby. You might have thought that the functionalities provided by these variables are already achievable with SASS, especially with SASS functions and types (like lists and maps), which enhance the flexibility of variable usage.
However, what I want to share here is where CSS variables truly shine.
This article assumes that you already have some basic understanding of CSS variables.
By the way, this article won’t cover a comprehensive guide on how to use CSS variables, so feel free to provide any suggestions. I will look for an opportunity to write a more thorough piece later.
Support
Browser | Version |
---|---|
Chrome | 49 |
Firefox | 42 |
Safari | 9.1 |
Custom Property
They only outperform traditional pre-processors when you treat them like properties.
First, it’s important to clarify that in the CSS spec, what we refer to as variables are actually called custom properties
. What does this mean? The distinction between variables and properties can be quite confusing!
Don’t worry; it simply means that when using CSS variables, we should think of them as regular CSS properties rather than just typical variables. Below, I’ll introduce some usage scenarios of CSS variables.
Why You Should Use CSS Variables
- You don’t need a pre-processor to use these properties.
- You can establish hierarchy using
initial
orinherit
. - Browsers will re-render when needed.
- You can access and manipulate them with JavaScript (more on that later).
Property Features
Since they are CSS properties, CSS variables come with the following features:
- They can use values like
initial
andinherit
. - They are called using
var(--variable-name)
. - They can be placed in
inline-style
. - You can get and set their values using JavaScript.
The standout features are the ability to use them in inline styles and their integration with JavaScript for getting and setting values. This is a significant departure from traditional CSS pre-processors like SASS and LESS, opening up new possibilities for CSS. Let’s look at some examples!
:root {
--mainColor: #abc;
--subColor: #ccc;
}
h1 {
color: var(--mainColor);
}
Here, the element declared in :root
will inherit across all elements, showcasing the nature of custom properties
.
Inline Style
Since they are properties, you can certainly write them like this:
<h1 style="color: var(--mainColor);">
Hello, world
</h1>
This may not seem particularly remarkable, as you can achieve the same effect using classes and SCSS variables. However, it does provide us with more options when writing inline styles.
React Inline Style
For instance, in React, we might need to write some inline styles, but defining colors can often feel awkward without SCSS control. You end up either hardcoding color values, making it cumbersome to change them later, or maintaining a separate JavaScript object for color variables. The best approach might be to assign a class to each color variable.
Now, with CSS variables, we can use them conveniently.
const styles = {
heading: {
fontSize: "14px",
color: "var(--mainColor)",
},
warn: {
color: "var(--warnColor)",
},
}
const heading = ({ title }) => <h1 style={styles.heading}>{title}</h1>
This article focuses solely on introducing CSS variables; there are many other excellent React style management approaches available.
Grid
When setting gutters, we can now use CSS variables. This means we can assign values to variables using @media queries
, something traditional pre-processors cannot do.
JavaScript Control
Through JavaScript, we can easily set or get CSS variable values, achieving separation between view and JavaScript logic. For example, if we want to pass some values from JavaScript to CSS, we typically calculate values in JavaScript and apply them as inline styles.
However, this may lead to some issues:
- The value might not be what I want, or I may want to manipulate it further, requiring tedious modifications to the JavaScript code.
- Since we are using inline styles for setting values, CSS becomes powerless.
With CSS variables, getting and setting values becomes incredibly straightforward.
Getting Values
HTMLElement.style.getPropertyValue("--mainColor")
Setting Values
HTMLElement.style.setProperty("--mainColor", "#abc")
Thus, we can also apply event listeners to inject values of interest into our variables.
const element = document.addEventListener("mousedown", e => {
// some HTMLElement;
element.style.setProperty("--pageX", e.pageX);
element.style.setProperty("--pageY", e.pageY);
});
Support
To check if the current browser supports CSS variables, you can use the CSS.supports
syntax.
CSS.supports('(--css: variables)')
CSS.supports('not (--css: variables)')
Future Challenges
As the management of variables becomes more complex, particularly with JavaScript manipulating their values, we should exercise caution when controlling these variables.
- Consolidate variable declarations: Keep global variables in a single file or folder for easier management, this also applies to declaring CSS variables.
- If a variable is meant for JS to set values, consider adding a prefix as a marker, such as
--js-pageX
, etc.
Conclusion
This article introduced the usage and scenarios of CSS variables. I previously thought CSS variables were cumbersome; they not only looked unattractive but also lacked corresponding functional operations.
However, once you grasp the concept that CSS variables are custom properties, you'll discover possibilities that CSS couldn't previously achieve. We don't necessarily have to choose between SASS and CSS variables; we can even combine both to create powerful effects that were previously unattainable.
If you found this article helpful, please consider buying me a coffee ☕ It'll make my ordinary day shine ✨
☕Buy me a coffee