CSS Image Sprites

  • Revision slug: Web/Guide/CSS/CSS_Image_Sprites
  • Revision title: CSS Image Sprites
  • Revision id: 495123
  • Created:
  • Creator: kscarfone
  • Is current revision? No
  • Comment Updated tags

Revision Content

Introduction

Image "sprites" are used in numerous web apps where multiple icons are used. Rather than include each icon as a .png image file, it is much more memory and bandwidth-friendly to send it as a single image.

Implementation

Suppose an image is given to every item with class toolbutton:

<style> .toolbtn {background:url(myfile.png); display:inline-block; height:20px; width:20px } </style>

A background position can be added either as two x,y values after the url() in the background, or as background-position. For example:

<style>
#btn1 {background-position: -20px 0px}
#btn2 {background-position: -40px 0px}
</style>

This would move the id=btn1 element left 20, and the id=btn2 element left 40 (assuming they have class="toolbtn", and are affected by the image rule above).

Similarly, you can also make hover states with:

#btn:hover {background-position: [pixels shifted right]px [pixels shifted down]px; }

Further reading

Full working demo: http://css-tricks.com/snippets/css/perfect-css-sprite-sliding-doors-button/

 

Revision Source

<h2 id="Introduction">Introduction</h2>
<p>Image "sprites" are used in numerous web apps where multiple icons are used. Rather than include each icon as a .png image file, it is much more memory and bandwidth-friendly to send it as a single image.</p>
<h2 id="Implementation">Implementation</h2>
<p>Suppose an image is given to every item with class toolbutton:</p>
<pre>
&lt;style&gt; .toolbtn {background:url(myfile.png); display:inline-block; height:20px; width:20px } &lt;/style&gt;</pre>
<p>A background position can be added either as two x,y values after the url() in the background, or as <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background-position">background-position</a>. For example:</p>
<pre>
&lt;style&gt;
#btn1 {background-position: -20px 0px}
#btn2 {background-position: -40px 0px}
&lt;/style&gt;</pre>
<p>This would move the id=btn1 element left 20, and the id=btn2 element left 40 (assuming they have class="toolbtn", and are affected by the image rule above).</p>
<p>Similarly, you can also make hover states with:</p>
<pre>
#btn:hover {background-position: [pixels shifted right]px [pixels shifted down]px; }</pre>
<h3 id="Further_reading">Further reading</h3>
<p>Full working demo: <a href="http://css-tricks.com/snippets/css/perfect-css-sprite-sliding-doors-button/">http://css-tricks.com/snippets/css/perfect-css-sprite-sliding-doors-button/</a></p>
<p>&nbsp;</p>
Revert to this revision