Using CSS background-image to style links

There are many ways to style links with CSS. One possible way is to use the background-image property to distinguish the various link states.

Link states are represented in CSS by selectors involving the a element, which targets an HTML a tag in a link like <a href="somepage.html">Some page</a>. The potential states of a hyperlink are link, visited, hover, active, and focus. In CSS rules, these selectors are written as:  a:link, a:visited, a:hover, a:active, and a:focus.

Let’s assume you have a set of images suitable for link backgrounds. These images might involve color changes, show small arrows or glyphs, or various other small but meaningful graphic enhancements meant to indicate link states. Further, assume the images are named hoverbg.jpg, linkbg,jpg, and visitedbg.jpg.

Start with the normal link state, a CSS selector that will style all your links until overruled by a subsequent rule.

a:link {
background: url(img/linkbg.jpg)
}

This will put your background image behind the text of you links. The next rule in your CSS should style visited links.

a:visited {
background: url(img/visitedbg.jpg)
}

Any visited link will now have a different appearance to your user.

Finally, add a rule to style the links while they are in the hover state or in the active state. You can use a group selector for this.

a:hover, a:active {
background: url (img/hoverbg.jpg)
}

This rule will style the link while is is hovered over or being clicked.

You could add a:focus to the group selector in the last rule, although I’m not sure it would be that useful in this scenario. Focus states are important to users browsing with assistive devices and visual difference like background images may not be relevant to them. Focus states are important to users who use the keyboard to move from link to link.

6 thoughts on “Using CSS background-image to style links”

    1. A good point, Mark. Using the sliding doors technique, which I didn’t mention, can reduce image load time, depending on what you want to do with the background. A small arrow or glyph used as a current page indicator can be a very small graphic to download.

  1. Glen, This is a fairly old post. Today, I would use CSS to create a background color or perhaps a gradient to signify link states. You can see an example of that in the blog’s menu, where the background on a:hover is a different color than other link states.

Leave a Reply