Background Color Test

by Kyle Mitofsky

HTML

<div id="a1" class="bg-color-purple">
  <code>.bg-color-purple { background-color: purple; }</code>
  <div id="a2"> Unstyled </div>
</div>

<div id="b1" style="background-color: purple;">
  <code>style="background-color: purple;"</code>
  <div id="b2"> Unstyled </div>
</div>

<div id="c1" class="bg-purple">
  <code>.bg-purple { background: purple; }</code>
  <div id="c2"> Unstyled </div>
</div>

<div id="d1" style="background: purple;">
  <code>style="background: purple;"</code>
  <div id="d2"> Unstyled </div>
</div>


<div style='position:fixed;bottom:0;left:0;background:lightgray;width:100%;padding:3px;'>
  About this question on SO
  <a href='https://stackoverflow.com/q/46336002/1366033'>
    How to get computed background color style inherited from parent element
  </a>
</div>

CSS

body {
  background: white;
}
div {
  border: 2px solid #d5d5d58f;
  border-radius: 4px;
  padding: 10px;
  margin: 10px;
  color: white;
}
code {
  font-size: 1.1em;
}

.bg-color-purple { background-color: purple; }
.bg-purple { background: purple; }

JavaScript

function getInheritedBackgroundColor(el) {
  // get default style for current browser
  var defaultStyle = getDefaultBackground() // typically "rgba(0, 0, 0, 0)"
  
  // get computed color for el
  var backgroundColor = window.getComputedStyle(el).backgroundColor
  
  // if we got a real value, return it
  if (backgroundColor != defaultStyle) return backgroundColor

  // if we've reached the top parent el without getting an explicit color, return default
  if (!el.parentElement) return defaultStyle
  
  // otherwise, recurse and try again on parent element
  return getInheritedBackgroundColor(el.parentElement)
}

function getDefaultBackground() {
  // have to add to the document in order to use getComputedStyle
  var div = document.createElement("div")
  document.head.appendChild(div)
  var bg = window.getComputedStyle(div).backgroundColor
  document.head.removeChild(div)
  return bg
}


/* test code */

// get all elements
var allDivs = [...document.querySelectorAll("div[id]")]
allDivs.forEach((el) => console.log(el.id, getInheritedBackgroundColor(el)))