Get Element's Custom CSS Properties (-Mystyle) Using JavaScript

Get element's custom css properties (-mystyle) using JavaScript

CSS values not understood by the browser are discarded, which explains why -my-custom-property was unavailable via .style.

In the past, you would have had to rely on storing the data with data attributes and dealing with inheritance yourself via JavaScript.

However, "custom properties", aka "CSS variables", have since been introduced into the standard and implemented by browsers, with ~92% support globally as of 2019-05-09. At a quick glance, Edge seems to have been the last major browser to implement, with version 16 on October 16, 2017.

Essentially, you need to set a custom property (eg, --my-custom-property: 'foobar';) on an element, and it can be accessed with something like getComputedStyle(your_el).getPropertyValue("--my-custom-property") which would return 'foobar' (with a leading space). Note the leading space and quotation marks. It will return the value exactly as it was provided.

Example:

console.log(getComputedStyle(document.getElementById("a")).getPropertyValue("--my-custom-property-1"))

console.log(getComputedStyle(document.getElementById("b")).getPropertyValue("--my-custom-property-2"))
#b-div { --my-custom-property-2: 'world' }
<div style="--my-custom-property-1: 'hello'"><h1 id="a">#a 'hello'</h1></div>

<div id="b-div"><h1 id="b">#b 'world'</h1></div>

Polymer 1.x: How to imperatively (using JS) obtain the value of a custom CSS property?

The docs you linked actually mention it...

You just need to check this.customStyle['--my-property-name'] and it will have the value of the property

Is it possible to use a block declaration as a CSS Custom Property?

A custom property is just that: an individual CSS property, with exactly one value. This value just happens to be usable in other property values via the var() function.

The value of a custom property cannot be a declaration block, because a declaration block is not a property value. By extension, a single custom property cannot substitute for multiple property declarations.

Whatever SCSS does with custom properties is non-standard and cannot be reproduced with a standard CSS stylesheet unless it's post-processed somehow (and even then, that's just pretending that custom properties can do more than what they're actually capable of by taking an additional dependency).



Related Topics



Leave a reply



Submit