Tuesday, June 19, 2012

CSS and Icon sprites - tips and tricks

[NOTE : This post was originally published on  BootStrapToday blog as "CSS and Icon sprites – tips and tricks"]

We used image sprites for icons on for version 2.0 and also in the latest version that we are working on (version 3). Quickly I realized that making sure that the icons looks same on major browsers is a task in itself.  For example, when you have an empty 'span' element which is supposed to display the icons, different browser will treat it slightly differently. Some browsers will give it a height/width of 1 character, some browsers height same as line height but width will be 0. If your icons are not arranged properly then putting those icons on buttons with consistent look & feel is a nightmare.  So here are few tips to define the icon image sprites and to use them effectively.

  1. First and most important tip is to have single sized icons in one sprite and arrange them in a grid. So if you have two icon sizes (e.g. 16px and 24px), make two sprites. One for 16px icons arranged on 16px X 16px grid. Another for 24px icons arranged on 24px X 24px grid.  Check the twitter-bootstrap icons.

  2. Use LessCSS or (some other equivalent) to define the icons css.

  3. Use span as 'display:inline-block'.  Typically span elements are inline elements. And you cannot define width/height of an inline element. Since we need to place the icons inline but need the flexibility of defining width/height, use 'display:inline-block'.

  4. Usually set the 'vertical-align:text-top'. This will align the icons to text.

  5. Use content:"". It will satisfy browsers which need to see text inside the span.
Here is a sample .less css fragment to be used with an icon sprite and
@icon-sprite-path:url(../images/icongrid.png);     /* url of the image path */

.icongrid {

/* the element should be placed as 'inline' but we need flexibility to define width/height, padding etc*/

/* to ensure that each span is 'icon-grid-size' by 'icon-grid-size' square */

/* to satisfy browsers which don't like empty elements */

/* align the icons with text */


/* define individual icon positions in sprite */
.testicon { background-position:0 -16px; }

Now you can use the icons with spans. For example to append the 'test icon' to some text, use
<div> ... your text here
<span class='icongrid testicon"></span>

Acknowledgement : I picked up some of these ideas by going over the twitter-bootstrap css and icon sprites.


Reno Computer Repairs and Website Development Services said...

Thanks for sharing! Good information

Web site Optimization | Hellbach blog said...

[...] CSS and Icon sprites – tips and tricksFrom Book of SpeedCSS Sprites generator (online maker)SpriteMe (online maker)Generate CSS sprites and thumbnail images on the fly in ASP.NET sites (search the site for more sprites) [...]