Styling Links with CSS

One aspect of CSS styling that some times can be confusing is styling links. This is because they are governed by both pseudo elements and specificity. Let's take a closer look.

Pseudo elements are tags that CSS recognizes, that attach to HTML tags, but are not put directly into the HTML markup. We see this most often used with hyperlinks and anchor tags.

CSS uses four pseudo elements to style links:

:link The link pseudo tag is used for all links on the page that point to other locations that have NOT been visited. Here's an example


a:link {
color: blue;
text-decoration: none;
}

Normally a link is underlined by your browser. If you don't want your link underlined you can shut the underline off with the text-decoration: none;.

The next tag is ":visited." These are sites that you have clicked on, visited, and then have returned to your page.


a:visited {
color: orchid;
}

Note the pseudo classes, " a:visited" for example,  is attached directly to the html tag with a colon, no spaces.

":hover" This styling will happen when your pointing device, or mouse, moves over the tag.  You do not have to actually click on the tag for hover to work.  This tags is used with the "img" tag to swap images when your mouse rolls over a picture. You can use this with other tags, like a table row.


tr:hover {
background-color: yellow;
}

Finally, we have ":active"   This styling is applied when an element has focus. Typically this is used with forms when you click in a form input box, or tab to it,  to type your name for example.


input:active { background-color: orange; }

Those are the basics, now let's get a little more specific, pun intended, and why some people's pseudo styling doesn't work the way they thought they had styled their tags. It turns out that pseudo tags all have the same specificity in CSS. That means that:

 a:link {color: blue;}
 a:active {color: orange;}
 a:hover {color: yellow;}
 a:visited {color:orchid;}

All are equal in terms of specificity in CSS. And according to the Cascade Styling rules, if specificity is equal, the last styling gets the nod. In the above order, if any of your links become visited, then, from then on, your link will show only the orchid color. Not quite what you want, so visited needs to be listed higher up, first or second.

In order for your links to perform properly, like you expect, they need to be listed in the correct order which is:

 a:link {color: blue;}
 a:visited {color: orchid;}
 a:hover {color: yellow;}
 a:active {color: orange;}

Link and Visited are mutually exclusive, in terms of which applies, so they can be listed in either first or second order interchangeably. Again: visited, link, then hover, and finally active: vlha, or "Very Lean Hungry Apes" as a memory aid. Enjoy, and good CSSing to you.

Comments are closed.