Create CSS Icons Using Pseudo-Classes and the Content Property
Displaying icons consistently across your website can be a mind-numbing task.
<img> tags is a terrible way to do it, and creating complex CSS with background images is a pain.
:before pseudo-class. The
:before pseudo-class combined with the
content property is great for displaying icons like this:
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.)
Get some icons and upload a few to your images folder. Between 22px and 32px square should work best, depending on your application.
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.
Add your CSS. We’ll apply the global styles using the
.icon class, and display the image using the
You’ll notice the blue box included in the
.icon code, you can ignore this if you want. The important part is in the
padding: 5px 8px;
border: 1px solid #bdd0e8;
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:
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:
Now go get cracking!