0 Inheritance in CSS

What does inheritance mean aside from the “inherit” value for CSS definitions? Well actually it means that conflicts can happen more than you realize.

Inheritance in CSS is rarely considered when writing styles for your website. More designers than anyone is willing to admit rarely ever organize their definitions in such a way that none of them conflict with each other or with new definitions. So how does it work (this assumes you understand basic CSS concepts)?

Top, Down and Shake it all around

CSS is loaded top-down. What this means is that whatever definitions are at the bottom of your CSS file, those will get the highest priority and will inherit whatever is missing from previous definitions with the same name. So for example, lets say I have some definitions like so:


// CSS EXAMPLE
.black {
  color: orange;
}
p.black {
  font-family: Arial;
  background: green;
}
#container .black {
  background: #000;
}

// HTML EXAMPLE

<p class="black">I'm the original foo!</p>

<div id="container">
  <p class="black">This is foo!</p>
</div>

Basically what I am doing in the above example inheriting the .black attributes for use with #container .black. But this inheritance only takes place inside #container. So our p element inside #container inherits color and font-family attributes from previous definitions of .black. In the example, .black originally defined font-family and color attributes. Because those are missing from #container .black, it will be inherited automatically along with any other missing attributes held by other .black css classes previously defined

When inheriting, context is important. div .black works the same as #container .black, but the only requirement is that #container be applied to a div element like so: <div class="container"></div>. div is the context just as in the example, p tag was the context for the .black class definition.

The more definitions your css file has, the more complex inheritance will become. So keep things as lean as possible and don’t forget to merge definitions into single definitions like I’ve done below. And if you need additional attributes for a specific definition that has been grouped, just copy and paste it as its own definition and go forth adding your addition attributes.


.black, #container .black, p.black {
  color: orange;
  font-family: Arial;
  background: #000;
}

p.black { 
  /* ADDITIONAL ATTRIBUTES IF NECESSARY */
}

Conclusion

Once you wrap your head around this whole inheritance bit, it will be easier to create stylesheets that are both extensible and maintainable without (mostly) any problems.