Saturday, February 18, 2006

Love Hate (LVHA)

CSS Link Specificity


Love Hate is how I taught myself to remember the order. The acronym for the order (LVHA) just wasn't terribly easy to remember on its own. It didn't spell anything, or really give a sensical meaning to me. But Love Hate works. So what is LVHA?
  1. a:link
  2. a:visited
  3. a:hover
  4. a:active

LVHA is the order you should designate your link rules in the CSS so they work together. The way that it is designed to work in CSS, each selector has a specificity. So, just like anything else in the cascade, if there are two selectors that are both applied to one element, the one with the higher specificity is applied. Put them in the wrong order, and you could end up with a page that isn't showing your style rules as you intended them.

The only two that you can change the order on are the a:link and a:visited (primarily because a link is only either or, never both). Now, keep in mind that you can change a multidute of things with links, but always keep in mind that specificity. To give an example of a potential problem, look at the following CSS:

Problem Order

a:link { background-color:white; color: blue }
a:active { background-color: blue; color: white;}
a:hover { background-color: black; color: white;}
a:visited {background-color:white; color:green;}


If you use the above CSS, all of it will work Except the active rules. Those will not show. Why? As I said earlier, visited and link do not have to be in a specific order (though ideally they should be in the LVHA order to keep consistency), but the active has to come after the hover. Due to the active being placed before the hover, that part breaks. Simply swapping the places of the active and hover (within the CSS) will fix the order of the cascade and allow it to all work.

In CSS2 we were able to combine our pseudo-classes, so that we could customize it further. An example being that you could have a regular hover for a link, but make it different for a visited link:

a:visited:hover {background-color: green; color: black;}

Again, specificity isn't terribly complicated on links if you follow the rule order. There are several articles on this topic, but in general, it doesn't get rough unless you aren't following the order.

~Nicole

Cross-posted to take your comments on Beyond Caffeine.