How I Learned To Love CSS Inheritance
Aug 31, 2006CSS has always been a bit of a conundrum to me. While in theory it’s a very simple way to easily style markup elements it has many little gotchas, most of which relate to the box model. One thing that has made my life a lot easier concerning CSS is finally understanding and using CSS inheritance.
What this means is that you can apply styles to nested elements and only nested elements without affecting the site wide styles.
This is best seen by example:
Let’s say we have an unordered list of links.
<ul class="mylist"> <li><a href="http://somewhere.com/">link1</a></li> <li><a href="http://foo.com/">link2</a></li> <li><a href="http://bar.com/">link3></a></li> </ul>
And we want these links to be a different color than the rest of the links on the page. This can be taken care of in the stylesheet using inheritance.
ul.mylist a {
color: red;
}
So now all the links with the parent class “mylist” will be the color red. What this does is make your HTML a bit cleaner, your CSS easier to read, and prevents having to come up with meaningful class or id names for everything.
If you want another good post on the subject here’s one by CSS guru Dan Cederholm.