CSS Inherit for unknown Background Color is Actually Transparent

mavrosxristoforos picture mavrosxristoforos · Oct 27, 2013 · Viewed 35.1k times · Source

I am creating a tab-like functionality with <ul> and <li> elements, and I noticed this kind-of unexpected behavior with CSS background-color: inherit.
One would expect that inherit wouldn't actually mean transparent, but rather child.background-color == parent.background-color (forgive the pseudo-code).

My code is quite simple, but I have a problem: I'm developing for variable conditions. That means I could never know what background-color will be used with my code, and I don't want to introduce my own.

I have prepared a JSFiddle, in which the background is randomly set on page load, to imitate the randomness of my code's destination. The obvious problem is that the active tab looks awful with its background-color pre-set. So, I changed it to background-color: inherit. (see JSFiddle 2)

While this obviously solved the background issue, the border of the element below (cg_content) started showing again, because the inherit property, acts like transparent, instead of what it does when there is a set background-color.

Question is: Is there a way to make it inherit the actual background-color without Javascript?
If not, could you suggest a better way to make these tabs look good without pre-set colors?

P.S.: The content <div> should not be a child element of the <li> elements, as these tabs share some contents.
P.S.2: I can't make it any more clear, that I obviously know how to do this with JS. I just don't want to.

Answer

Quentin picture Quentin · Oct 27, 2013

Setting background-color: inherit does cause it to take the background colour of the parent element.

The reason it is taking transparent is because the background colour of the parent (the li) is transparent (the default value).

The only other element in your second JSFiddle which has a background colour set is #unknown_background, which is the anchor's great-great-grandparent.

Add div, ul, li { background-color: inherit; } to the end of your stylesheet and the background will be inherited all the way down and the border will not show up.