Using Custom Properties with JavaScript in CSS

Remember: custom properties are CSS properties, and we can interact with them as such. For example, we can use the css.supports() API to test whether a browser supports custom properties:

const supportsCustomProps = CSS.supports(‘–primary-text: #000’);

// Logs true to the console in browsers that support custom properties console.log(supportsCustomProps);

You can learn more about the css.supports() API, as well as the @supports CSS rule, in Chapter 10, “Applying CSS Conditionally”.

We can also use the setProperty() method to set a custom property value:‘–bg-home’, ‘whitesmoke’);

Using removeProperty() works similarly. Just pass the custom property name as the argument:‘–bg-home’);

To use the custom property as a value with JavaScript, use the var() function with the property name as its argument: = ‘var(–bg-home)’;

Alas, you can’t set custom properties using square-bracket syntax or camelCased properties of the style object. In other words, neither–bg-home nor[‘–bg-home’] will work.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *