Using background images with links
Associating icons with links can in my opinion be a powerful design device. With a small amount of CSS it is simple to add icons into your links.
To apply an icon to links in CSS you use background-image. Although you should use icons on links sparingly icons can greatly improve the usability of a site. In this example we have a link that goes to a journal entry page. Make an icon using Illustrator, Photoshop or your favorite imaging software. Make sure that it relates well to the size of the text it appears next to. Here I’ve made a simple pencil:
The Markup ¶
In this example we have a simple link within a div
<div id="example-link">
<a href="#">Link to journal article</a>
</div>
The CSS ¶
#example-link a {
padding-left: 15px;
background: url(/images/examples/bglinks/pencil_icon.gif) 3px 1px no-repeat;
}
Explanation: ¶
Padding left - This moves the text away from the image. Depending on the width of your image you will need more or less padding
Background - This has the rules associated with the the background image
- url(/images/examples/bglinks/pencil_icon.gif) - This is the path the image you want to be your icon.
- 3px 1px - These values position the background image. The first value is the background image’s distance from the left of the a tag, the second is the distance from the top of the a tag.
- No-repeat tells the browser only to show the image once.
The code in action ¶
A simple icon applied to a link using CSS. (If you are reading this in a newsreader you won’t see the image)
Tags
Can you help make this article better? You can edit it here and send me a pull request.
See Also
-
Writing good XHTML and CSS Part 2
The second in a series of good practices for writing XHTML and CSS looking at writing clean, maintainable code and dealing with browser hell problems. -
Preparing for IE7 - Limiting CSS Hacks
Internet Explorer 7 is just around the corner and there have been warnings from Microsoft that existing hacks will break layouts in IE7. By limiting the use of hacks your CSS can be both backwards and forwards compliant. -
Writing good XHTML and CSS Part 1
In two articles I’m going to outline my opinion on what you need to understand and write high quality XTHML and CSS. The articles will focus on producing code that stands up to the rigors of the web and future proofs code. The articles are aimed at coders starting out and looking to get to grips with writing professional front end code. Of course if you don’t agree with something the comments box is there for you to add your opinion. In part 1 I’m going to look at what you need to get off the ground.