There is no reason to use jQuery for this! : -) You can use the method getPropertyValue
, available in prototype type objects CSSStyleDeclaration
.
A simple example:
// Equivalente ao pseudo-seletor `:root` no CSS.
const root = document.documentElement;
// Define uma "variável" na raiz:
root.style.setProperty('--my-var', 'rgb(255, 0, 0)');
// Obtém a "variável":
const result = root.style.getPropertyValue('--my-var');
console.log(result); //=> rgb(255, 0, 0)
The problem is that using getPropertyValue
in CSSStyleDeclaration
returned by property style
of any element will not work to get the "variavies" defined by the CSS, since the property style
recovers only defined styles inline in the element itself.
To get CSS "variables" defined in the stylesheet, you must use the CSSStyleDeclaration
returned by the method getComputedStyle
by application with the element itself.
An example:
// Obtém a raiz:
const root = document.documentElement;
// Obtém os estilos computados para a raiz:
const computedStyles = window.getComputedStyle(root);
// Obtém a "variável":
const result = computedStyles.getPropertyValue('--my-var');
console.log(result); //=> rgb(255, 0, 0)
:root {
--my-var: rgb(255, 0, 0);
}
Since computed styles inherit CSS rules defined on any parent element, you can use this artifice on any descending element of the root element.
However, to facilitate the computation of styles, always search for the closest element to the one that defined the rule. In this case, the :root
.
Regarding "observing changes" automatically, there is no defined way to do this. One option is to encapsulate the logic I showed above in a function and call it whenever the user changes the resolution.
You can do this type of invocation by issuing the event resize
, for example.
This response was based in this question (and answers) soen.
"css variable?" variable o property? want to read the value of
--limite
that’s it?– Ricardo Pontual
That’s right, CSS variable, not property!
– Carlos Rocha