getComputedStyle('background-color') returns transparent, does not inherit ancestor's
It's because background-color property is not inherited by the children elements (unlike the color property).
You can read more at: https://developer.mozilla.org/en-US/docs/Web/CSS/inheritance
Is color format specified in the spec for getComputedStyle?
CSSOM does not state this directly, but instead references css-color-4:
To serialize a CSS component value depends on the component, as follows:
<color>
If <color> is a component of a resolved value, see CSS Color 4 §4.6 Resolving <color> Values.If <color> is a component of a computed value, see CSS Color 4 §4.7 Serializing <color> Values.
For the purposes of getComputedStyle()
, both of the above lines mean the same thing. Specifically, section 4.7.2 covers the majority of commonly used formats:
4.7.2. Serializing sRGB values
The serialized form of the following sRGB values:
- hex colors
rgb()
andrgba()
valueshsl()
andhsla()
valueshwb()
values- named colors
is derived from the computed value and thus, uses either the
rgb()
orrgba()
form (depending on whether the alpha is exactly 1, or not), with lowercase letters for the function name.
Section 4.7.6 covers system colors (computes to lowercase), transparent
(computes to rgba(0, 0, 0, 0)
) and currentColor
(computes to lowercase currentcolor
).
As css-color-4 introduces several new ways to specify colors, other sections exist for other formats such as §4.7.3 for LCH values, §4.7.4 for the color()
function, and more.
This means that color values from getComputedStyle()
are guaranteed to be in either rgb()
or rgba()
format, depending on the alpha value, only when the specified values are in any of the formats in §4.7.2. But §4.7.2 and §4.7.6 cover the vast majority of use cases in everyday CSS, so they can still be relied on. Considering the other, exotic formats aren't really supported anywhere yet, it's probably not worth testing for them until they enjoy any sort of mainstream use.
How to get element color which has no background?
There is no way to calculate the background of TOP3. If its background is not set, it is transparent. As such, it has the color of whatever is below it.
Example:
<div style="background: red; width: 100px; height: 100px">
TOP1
<div style="background: green; width: 80px; height: 80px">
TOP2
<div style="width: 60px; height: 100px; border: solid 1px yellow">
TOP3
</div>
</div>
</div>
Getting the real background-color of an element?
Try window.getComputedStyle
:
window.getComputedStyle(element, null).getPropertyValue("background-color")
This approach is simple and native, but doesn't support IE8
Two ways to get background-color property using Javascript
Checkout this link
The getComputedStyle() method is used to get all the computed CSS property and values of the specified element. The use of computed style is displaying the element after stylings from multiple sources have been applied. The getComputedStyle() method returns a CSSStyleDeclaration object.
In other words, the returned value from both calls can be different, since the computed style will be the result of applying all rules for the element.
The element CSS reads what we set directly on the element, which can be overwritten by another rule on another element (its parent for example).
How to get backgroundColor of element when it is set by the CSS property background?
When you access the style
(ElementCSSInlineStyle.style
) property of an element, you are accessing its inline style. This means that if you give an element a style via a class, you still cannot access it through style
. As a result, it will return you an empty string (''
).
Window.getComputedStyle
, on the other hand, returns:
... the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain
This means that you can access the style that is given via a class, simply because it gives you all CSS properties after applying all active stylesheets (including those applied via a class).
In your particular case, you're trying to access background
. background
CSS property is actually a shorthand that also sets a lot of other background-related CSS properties. When you specify only the color using background
, the other properties will automatically be inserted with their default values. You can access this background
property through ElementCSSInlineStyle.style
. However, when accessing background
in the object Window.getComputedStyle
returns, you will always get an empty string. This is because the object returned does not have the key background
; it only has the keys for each background-related CSS properties (e.g. background-color
, background-clip
, etc.).
Here's a simple example demonstrating how you cannot access a non-inline style through style
property of an element, and also how you cannot access the value of a property that is shorthand through the object Window.getComputedStyle
const boxOne = document.querySelector('#boxOne')const boxTwo = document.querySelector('#boxTwo')
console.log(`Box One: background ${boxOne.style['background']}, background-color ${boxOne.style['background-color']}`)
console.log(`Box Two: background ${boxTwo.style['background']}, background-color ${boxTwo.style['background-color']}`)
const boxOneComputedStyles = getComputedStyle(boxOne)const boxTwoComputedStyles = getComputedStyle(boxTwo)
// There's no 'background' key in getComputedStyle
console.log(`Box One (Computed Styles): background ${boxOneComputedStyles['background']}, background-color ${boxOneComputedStyles['background-color']}`)
console.log(`Box Two (Computed Styles): background ${boxTwoComputedStyles['background']}, background-color ${boxTwoComputedStyles['background-color']}`)
#boxOne,#boxTwo { background: #121212DD; border-radius: 5px; width: 50px; height: 50px; margin: 1em;}
<div id="boxOne" style="background-color: #121212DD;"></div><div id="boxTwo" style="background: #121212DD;"></div>
About js to Get background Color
That's because style
refers to the inline style
attribute in your HTML. If you want to get the style
that's set via CSS only, you will need to use computedStyles
.
const elem = document.getElementsByTagName('p')[0]; // get elementconst styles = window.getComputedStyle(elem); // get computed style of elementconsole.log(styles.getPropertyValue('background-color')); // get specific attribute
p { background-color: red;}
<p>Hi!</p>
Getting background-color of body in iframe
You can access it with JavaScript using .getComputedStyle()
of the iframe's body by selecting .contentWindow.document.body
then selecting the body's background color.
var iFrameEl = document.getElementById('my-iframe');
var backgroundColor = iFrameEl.contentWindow.getComputedStyle(iFrameEl.contentWindow.document.body).backgroundColor;
Related Topics
Attempt to Add a Rule to a CSS Stylesheet Gives "The Operation Is Insecure" in Firefox
How to Get New Image Size Dimension After Giving Object-Fit:Contain Property to the Image Tag
Bootstrap 4 Input Field in Popover
Disable Double Tap Zoom/Resize on Safari iOS12***
Angular - Ngfor* Four Elements on Row
Centering Textarea Placeholder Text in Safari
How to Start CSS3 Animations at a Specific Spot
JavaScript - Page Has to Be Refreshed to Show Particle-Slider Logo Effect
Background Image Resizing to Fit
Is There Js Plugin Convert the Matrix Parameter to CSS3 Transform Property