CSS link declaration efficiency
December 13, 2005 /
Filed under: CSS, Efficiency, Web Development
Often on web pages, links in one section of the page look different than links in another section of the page. This could be due to, perhaps, different background colors - where the default link styles don’t "blend" or "match" well, in one area, versus another. So, it’s quite common to create two (or more) sets of link style declarations - all of which apply to various "sections," or "areas" of the page. Using descendent selectors in CSS - it’s quite easy to manage multiple link styles. For example, let’s say the following CSS are my default link styles:
a:link
{
color: yellow;
text-decoration: none;
}
a:visited
{
color: gray;
}
a:hover
{
color: #ffc;
text-decoration: underline;
}
a:active
{
color: red;
}
Every link will inherit these properties, unless preceded with another selector:
.rightcolumn a:link
{
color: blue;
text-decoration: none;
}
.rightcolumn a:visited
{
color: gray;
}
.rightcolumn a:hover
{
color: #ffc;
text-decoration: underline;
}
.rightcolumn a:active
{
color: red;
}
So, all links in my "right column" will be the color blue, instead of yellow. Efficient code: Combining "like" selectorsMy problem comes from having to re-declare all four psuedo-classes, every time I want to simply change the color of a link, in a certain section of a site. It’s OK when there’s only two different link colors - but for any more - the CSS code becomes bulky. Doesn’t CSS teach us to combine "like" selectors? From those two code samples above, you’ll notice the only change I made (in the second set) was the color of blue. For the rest of the selectors (which are identical), why not combine them:
a:visited,
.rightcolumn a:visited
{
color: gray;
}
This is much more efficient code, if you ask me. Physically moving codeThis doesn’t solve our problems, though. By combining "like" selectors, we could be physically moving the CSS code out of order:
a:link
{
color: yellow;
text-decoration: none;
}
a:visited,
.rightcolumn a:visited
{
color: gray;
}
a:hover
{
color: #ffc;
text-decoration: underline;
}
a:active
{
color: red;
}
.rightcolumn a:link
{
...
}
Notice how Love, Hate your linksIn order to ensure the most consistency across all browsers, links should be declared as such:
If you extract the first letter from each - you can compose a small pnemonic device - "LoVe, HAte," which helps you always remember the correct order. (This pnemonic device was not invented by me - it’s rather famous in the web community - although I’m not sure who "coined" the term.) The point is... if we physically move style selectors to other areas of the page, then they don’t remain in the proper, "Love Hate" order, which means inconsistency across browsers, namely IE6. Comments/Mentions |
Recent Comments
Recent Music Listens
|