SiteKickr Web Development

CSS Sprites – the elegant way

I was trying to come up with a way to use image sprites for background images, without needing to specify a ton of class names.

The usual method would be:

<ul>
  <li class="class1"><a href="">Item 1</a></li>
  <li class="class2"><a href="">Item 2</a></li>
  <li class="class3"><a href="">Item 3</a></li>
</ul>

<style>
ul li a { background: url('icons.png') no-repeat; }
ul li.class1 a { background-position: 0 -30px; }
ul li.class2 a { background-position: 0 -60px; }
ul li.class3 a { background-position: 0 -90px; }
</style>

 

But, by leveraging the next sibling CSS selector, we can avoid the need for classes or ids to identify our elements.

<ul>
  <li><a href="">Item 1</a></li>
  <li><a href="">Item 2</a></li>
  <li><a href="">Item 3</a></li>
</ul>

<style>
ul li a { background: url('icons.png') no-repeat; }
ul li a { background-position: 0 -30px; }
ul li + li a { background-position: 0 -60px; }
ul li + li + li a { background-position: 0 -90px; }
</style>