In styles for an element I have a few inline CSS declarations including a shorthand declaration for background
<style>
:root{
--bg-white: rgba(255, 255, 255, 0);
}
</style>
<div style="background: var(--bg-white); ... "></div>
but when iterating over HTMLElement.style the shorthand property looks like it’s wrongly expanded
for (const declaration of Array.from(target.style)) {
const value = target.style.getPropertyValue(declaration)
console.log(`${declaration}: ${value}`)
}
This should print out background-color: var(--bg-white)
per HTMLElement.style documentation on MDN, but I get background-color: ''
Shorthand properties are expanded. If you set style="border-top: 1px solid black", the longhand properties (border-top-color, border-top-style, and border-top-width) are set instead.
Has anyone encountered this before?
2
Answers
UPDATE the OP commented that he/she wants to get just the string value of the CSS rule. In our case that’s just a matter of getting and parsing the style attribute.
For more complex scenario for getting CSS rules from
<style>
refer to my another answer : Get the formula of a CSS value instead of the calculated value in JavaScriptThe previous answer:
Use
getComputedStyle()
to get the computed value. The shorthand properties are expanded the same way as instyle
.The
style
contains only inline styles assigned to the element and doesn’t calculate any css properties (inline and inherited). So thebackground-color
is empty in that case.https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
If you use
HTMLElement.style
, it will return what is directly applied (not computed) through thestyle
attribute.In that case the browser can’t know what the
var(...)
inbackground: var(--bg-white);
will resolve and to whichbackground-...
properties it will contain (The contents of the variable will be placed where thevar(...)
statement is and then the resulting value will be parsed.So if you e.g. have
--bg-white: content-box radial-gradient(crimson, skyblue);
then your--bg-white
will actually influence multiple properties.