Time for a little CSS puzzle! Today I was faced with an issue I couldn’t find a quick solution for. Take this CSS and HTML:
#foo p { color: red; }
.bar { color: green; }
<div id="foo">
<div class="bar">
<p>Some text</p>
</div>
</div>
I couldn’t change any of the above lines, and I didn’t know the exact color of the bar class, and yet the goal was to display the paragraph in that specific color – in this case green. So I couldn’t just make up a more specific selector and add color: green.
Found a solution yet? I was about to give up and refactor the whole thing, until one of our developers suggested me this:
#foo .bar p { color: inherit; }
A selector that is more specific, and tells the element to “look at your parent for the text color”. Call me stupid, but I totally didn’t think of it. Huzzah!
Of course there’s a certain browser that doesn’t play nice with inherit but that was quickly solved with a CSS expression:
#foo .bar p { color: expression(this.parentNode.currentStyle.color); }
So next time you run into something like this, remember your parent!