Styling Links in CSS

Styling links in CSS is easy. The color of a link and the behavior of a link can be controlled with CSS.

Controlling Link Behavior

The behavior of a link refers to how that link is displayed on a web page, what happens when a user hovers over it as well as what happens at the point it is clicked and after it is clicked.

A link has a specific format. That format is:

a:[condition] <----- The condition refers to the state of the link

The possible conditions are:

link ( refers to an unclicked link )
visited ( refers to a visited link )
hover ( when the mouse is placed over the link )
active ( when the link is active – has been clicked )

a:link

A link that has not been visited. This is the link as it normally appears. Normal links appear blue and underlined. Below, by using CSS, the color of the link is changed to display the color green and the default line usually found beneath all links is removed using the text-decoration property.

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

a:visited

A link that has been visited. After a link is clicked, the state of that link changes from a:link to a:visited. In this example, the color is set to change to purple and the text link to italics.

a:visited
{
    color: purple;
    font-style: italic;
}

Note: Remember that most other CSS properties (e.g. font-weight, font-family) can also be applied to a link. In this example only the color and font-style properties are applied.

a:hover

Movement of the mouse over a link. When a user hovers over a link any formatting specified by a:hover will be be reflected. In this example the font weight is set to display the link in bold.

a:hover
{
    font-weight: bold;
}

a:active

A link just when it has been clicked. Below, the color and font-variant properties are applied.

a:link
{
    color: #000000;
    text-decoration: small-caps;
}

Combining Link Behavior Into One

There are guidelines to follow when combining link behavior in a style sheet. These are:

The a:hover has to come after a:link
The a:hover must also come after a:visited
The a:active has to come after a:hover.

A properly defined layout is shown below:

a:link
{
    color: green;
    text-decoration: none;
}
a:visited
{
    color: purple;
    font-style: italic;
}
a:hover
{
    font-weight: bold;
}
a:active
{
    color: #000000;
    font-variant: small-caps;
}