Taking Advantage of CSS Inheritance

by cdwise 19. December 2011 21:45

I've been seeing a lot of posts asking for help with link styles on several of the mail lists and forums I belong to and thought I'd mention the benefits of using inheritance to slim down your CSS and make it a little easier to manage.

What I've been seeing is things like:

#menu a:link {
color: #CC0000;
text-decoration: none;
font: .85em Geneva, Tahoma, sans-serif bold;
}
#menu a:visited {
color: #808080;
text-decoration: none;
font: .85em Geneva, Tahoma, sans-serif bold;
}
#menu a:active {
color: #800000;
text-decoration: none;
font: .85em Geneva, Tahoma, sans-serif bold;
}
#menu a:hover {
color: #CC0000;
text-decoration: underline;
font: .85em Geneva, Tahoma, sans-serif bold;
}

Notice that you are repeating a lot of the same style property/definitions in each pseudo class when in most cases only one of the style definitions change. You can simplify this and make it easier to spot what changes in each pseudo class by using:

#menu a {
color: #CC0000;
text-decoration: none;
font: .85em Geneva, Tahoma, sans-serif bold;
}
#menu a:visited {
color: #808080;
}
#menu a:active {
color: #800000;
}
#menu a:hover {
text-decoration: underline;
}

By using the a instead of the a:link all of the properties you define are inherited by all pseudo classes so that you only need to change the properties that vary in the state you are defining. This cuts down on your CSS code AND has the added benefit of making it far easier to see what the differences are in that state from the default link.

Tags:

CSS

Comments are closed


Outstanding Hosting