Create CSS Icons Using Pseudo-Classes and the Content Property

Displaying icons consistently across your website can be a mind-numbing task.

Using <img> tags is a terrible way to do it, and creating complex CSS with background images is a pain.

Enter the :before pseudo-class. The :before pseudo-class combined with the content property is great for displaying icons like this:

PDF Download
MP3 Download

Or like this:

Title With Icon

A Smaller Title With Icon

Pseudo-classes have been around since CSS1 way back in 1996. The great part about the :before class is that it is supported in all major browsers, IE included! (Just make sure you declare a !DOCTYPE or it won’t work in IE8.)

Getting Started

Step One

Get some icons and upload a few to your images folder. Between 22px and 32px square should work best, depending on your application.

Step Two

Create your html:

<a class="icon pdficon">PDF Download</a>

Using two different classes allows you to write less CSS if you are reusing this across your site.

Step Three

Add your CSS. We’ll apply the global styles using the .icon class, and display the image using the a.pdficon:before class.

You’ll notice the blue box included in the .icon code, you can ignore this if you want. The important part is in the a.pdficon:before styles.

.icon {
display: block;
padding: 5px 8px;
background: #e6effa;
border: 1px solid #bdd0e8;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
}

.icon:hover {
background: #f4f8fd;
}

a.pdficon:before {
content: url(images/pdf-22.png);
display: block;
float: left;
margin-right: 5px;
position: relative;
bottom: 2px;
}

That’s it! Just change the a.pdficon:before class to something else to display a different image. For example, the code for the MP3 download above is:

a.mp3icon:before {
content: url(images/itunes.png);
display: block;
float: left;
margin-right: 5px;
position: relative;
bottom: 2px;
}

Notice the relative positioning – this is not always necessary, it just depends on how your icon is lining up.

Titles with Icons

The titles are the same concept, just slightly different code. Here’s the HTML from the larger title above:

<h2 class="widgeticon">Title With Icon</h2>

Here’s the CSS:

h2.widgeticon:before {
content: url(images/help-32.png);
display: block;
float: left;
margin-right: 5px;
}

Now go get cracking!