How to get computed background color style inherited from parent element

≡放荡痞女 提交于 2019-11-28 13:57:00

You apparently mean to ask

How do I find the background color for some element which is used by virtue of that color being set as the background color of some ancestor which shows through because all intervening elements having transparent background color?

However, your question is confusing because you are using the word "inherited", which has a very specific meaning in CSS, which is not relevant here.

The background-color property is not inherited in the CSS sense. Every element has its own background color, which by default is transparent.

The reason that you inner div looks like it has a papayawhip background is that actually it has a transparent background, which lets the papayawhip background of the outer div show through. There is nothing about the inner div that knows or cares about papayawhip, or that can be queried to return papayawhip.

The only way to find that the inner div is going to have a papayawhip background is to traverse the DOM tree and find the closest parent that has a non-transparent background color. This is explained in the question proposed as a dup target.

By the way, what is your underlying problem here? Why are you trying to do this? There are probably better ways.

add background-color: inherit; to your #innerDiv

document.addEventListener("DOMContentLoaded", function (event) {
  var inner_div = document.getElementById("innerDiv");
  console.log(getComputedStyle(inner_div, null)["backgroundColor"]);
});
#outterDiv {
  background-color: papayawhip;
}
#innerDiv {
  background-color: inherit;
}
<div id="outterDiv">
  <div id="innerDiv">
    I am an inner div
  </div>
</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!