Blog

Sprites and the :before element

Lets suppose you have a big sprite with icons place not only vertically, but also horizontaly, effectively creating a complex grid. Now lets suppose you want to create an <a> tag with an icon on the left side, and some text after that.

If you were to use a single icon, and not a sprite, you code would look something like this (px values are random):

<a> class="with-bg-icon">Hello there!</a>
.with-bg-icon {
padding-left: 16px;
background: url('icons/sprite.png') no-repeat 0 -32px;
}

If you try this with a complex sprite like the one described above, it wont work, as you’ll see all the icons placed on the right of the icon you need. The solution is to use the :before pseudo-element, and finally have something like this:

<a> class="with-bg-icon">Hello there!</a>
.with-bg-icon:before {
width:16px;
height:14px;
background: url('icons/sprite.png') no-repeat 0 -32px;
display: inline-block;
content:"\0020";
margin-right: 3px;
}

What :before does, is actually create an element inside the </a> tag, before anything else. We just set that element to inline-block and adjust the dimensions and everything looks great.

1 Comment

  • nikos

    Like Tzanis commented, I actually forgot to add :before. Fixed now

    Reply

Post A Comment