I have translated the Markdown content while strictly following the rules you provided:
I have previously written a blog post about my thoughts on CSS variables. Initially, I didn't have high expectations for this feature as I was already accustomed to using SASS variables, and I felt that CSS variables were like a less powerful system. However, if you share the same opinion, you can refer to this article: [Why should you care about CSS variables](https://developers.google.com/web/updates/2016/02/css-variables-why-should-you-care)
CSS variables have been around for some time now, and browser support is not too bad. Perhaps you have wondered why these variables are necessary when most of their functionality can be achieved with SASS, along with SASS functions and the flexibility of using data types like lists and maps.
However, I would like to share with you the truly remarkable aspects of CSS variables.
This article assumes that you already have some basic knowledge of CSS variables.
It's worth mentioning that this article does not comprehensively cover how to use CSS variables. Therefore, any suggestions are welcome, and I plan to write a more comprehensive article in the future.
### Browser Support
| Browser | Version |
| ------- | ------- |
| Chrome | 49 |
| Firefox | 42 |
| Safari | 9.1 |
### Custom Property
> **It becomes powerful only when you make it behave like a property**, surpassing the capabilities of typical preprocessors.
First, let's clarify that in the [CSS specification](https://drafts.csswg.org/css-variables/), variables are actually referred to as `custom properties`. What does this mean? Variables and properties are confusing!
Don't worry, when using CSS variables, we should think of them as regular CSS properties rather than ordinary variables. The following will introduce some uses of CSS variables.
### Why should you use CSS variables
- You can use these properties without needing a preprocessor.
- You can establish a hierarchy using `initial` and `inherit`.
- **Browsers will re-render when necessary.**
- You can access and manipulate them using JavaScript (more on this later).
#### Property Features
Since they are CSS properties, they possess the following characteristics:
- They can use values like `initial` and `inherit`.
- They are called using the syntax `var(--variable-name)`.
- **They can be placed inside `inline-style`.**
- **You can get and set their values using JavaScript.**
The most significant advantage is that they can be used within `inline-style` and can be easily accessed and manipulated using JavaScript. This is the major difference from preprocessors like SASS or LESS, and it opens up new possibilities for CSS. Let's look at some examples!
```scss
:root {
--mainColor: #abc;
--subColor: #ccc;
}
h1 {
color: var(--mainColor);
}
In this example, elements declared within :root
will inherit these custom properties.
Inline Style
Since they are properties, they can be written like this:
<h1 style="color: var(--mainColor);">
Hello, world
</h1>
This may not seem particularly remarkable because the same thing can be achieved using classes and SCSS variables. However, it adds another possibility when writing inline styles.
React Inline Style
For example, in React, we may need to write some inline styles, but specifying colors can be awkward since it is no longer under SCSS control. We either directly use color codes and later struggle to modify them, or we create a separate variable table using JavaScript. The best approach might be to assign a class to each color variable.
With CSS variables, we can easily achieve this:
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, but there are other excellent ways to manage styles in React.
Grid
We can now use CSS variables to set gutters. This means we can set variable values using @media queries
, which is something typical preprocessors cannot achieve.
JavaScript Control
Through JavaScript manipulation, we can easily set or retrieve CSS variable values, achieving a separation between view and JavaScript. For example, if we want to apply some effects by retrieving values using JavaScript and passing them to CSS. Typically, we might calculate values using JavaScript and then present them using inline styles.
However, this can lead to some scenarios:
- The value obtained may not be what we desire, or we may want to perform some additional operations on it. In such cases, we would need to modify the JavaScript code, which can be cumbersome.
- Since we are using inline styles, CSS has limited control.
With CSS variables, setting and retrieving values becomes very convenient.
Retrieving Values
HTMLElement.style.getPropertyValue("--mainColor")
Setting Values
HTMLElement.style.setProperty("--mainColor", "#abc")
Thus, we can also apply event listeners to inject interested values into our variables.
const element = document.addEventListener("mousedown", e => {
// some HTMLElement;
element.style.setProperty("--pageX", e.pageX)
element.style.setProperty("--pageY", e.pageY)
})
Browser Support
To check if the current browser supports CSS variables, you can use the CSS.supports
syntax for detection.
CSS.supports('(--css: variables)')
CSS.supports('not (--css: variables)')
Future Challenges
As the ways to manage variables increase, and JavaScript performs actions on these variables, we should be more cautious when controlling them.
- Handle variable declarations uniformly: Place global variables in a single file or folder for easier management. The same applies to declaring CSS variables.
- If variables are meant for JavaScript to set values, consider adding prefixes as markers, for example:
--js-pageX
, and so on.
Conclusion
This article introduced the usage and scenarios of CSS variables. I used to find CSS variables awkward, as they were not aesthetically pleasing to write and lacked corresponding functions.
However, once you understand that CSS variables are essentially custom properties, you will discover possibilities that CSS couldn't achieve before. We don't necessarily have to choose between SASS and CSS variables; we can even use them together to create powerful effects that were previously unattainable.