Question:

How can JS modify CSS pseudo-class styles? But JS doesn’t have a pseudo-class selector, so what can be done? There are a number of methods available on the web, such as switching element classes and dynamically inserting new styles in style.

So here is another method, set CSS variable (var), through JS to change the variable to achieve.

Example: Change the hover background color of div

<! -- css -->
<style type="text/css">
    :root {
        --divHoverColor: red;
    }
    div {
        width: 100px;
        height: 100px;
        background: bisque;
    }
    div:hover {
        background: var(--divHoverColor);
    }
</style>
<! -- html -->
<div onClick="onDivClick('green')"/>
<! -- js -->
<script type="text/javascript">
    function onDivClick(value){
        document.documentElement.style.setProperty('--divHoverColor', value);
    }
</script>
Copy the code

So, CSS variable

1. Basic usage

A local variable

div {
    --masterColor: red;
    background: var(--masterColor);
}
Copy the code

The global variable

/* For HTML, :root represents the < HTML > element */
:root {
    --masterColor: red;
}
div {
    background: var(--masterColor);
}
Copy the code

2. Grammar

var( <custom-property-name> [, <declaration-value> ]? )


: custom property name

: fallback value

Example:

div {
    Var (--masterColor, red, green) */
    background: var(--masterColor, red);
}
Copy the code

Variables can be referenced via var()

Example:

div {
    --masterColor: red;
    --bgColor: var(--masterColor)
}
Copy the code

Note: Attribute names cannot use variables

Examples of errors:

div {
    --bg: background;
    var(--bg): red;
}
Copy the code

3. Browser support

Can I use

Test using @support

@supports ( (--masterColor: red)) {
  /* supported */
}
@supports ( not (--masterColor: red)) {
  /* not supported */
}
Copy the code

Using JS detection

const isSupported = window.CSS && window.CSS.supports 
    && window.CSS.supports('--masterColor'.'red');

if (isSupported) {
  /* supported */
} else {
  /* not supported */
}
Copy the code

reference

MDN CSS Variable specification


Thank you for reading