[NOTE : This post was originally published on BootStrapToday blog as "CSS and Icon sprites – tips and tricks"]
We used image sprites for icons on bootstraptoday.com 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.
- 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.
- Use LessCSS or (some other equivalent) to define the icons css.
- 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'.
- Usually set the 'vertical-align:text-top'. This will align the icons to text.
- Use content:"". It will satisfy browsers which need to see text inside the span.
@icon-sprite-path:url(../images/icongrid.png); /* url of the image path */
@icon-grid-size:16px;
.icongrid {
background-image:@icon-sprite-path:
background-repeat:no-repeat;
/* the element should be placed as 'inline' but we need flexibility to define width/height, padding etc*/
display:inline-block;
/* to ensure that each span is 'icon-grid-size' by 'icon-grid-size' square */
padding:@icon-grid-size/2;
/* to satisfy browsers which don't like empty elements */
content:"";
/* align the icons with text */
vertical-align:text-top;
}
/* 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>
</div>
Acknowledgement : I picked up some of these ideas by going over the twitter-bootstrap css and icon sprites.
2 comments:
Thanks for sharing! Good information
[...] 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) [...]
Post a Comment