Background repeat and CSS sprites
CSS sprites are a great way to improve the loading speed of your pages. One of the problems you might face with sprites is how to deal with cases when the background repeats.
The rule is pretty simple: if you want the background to repeat vertically (top to bottom), place the images in the sprite horizontally (left to right) and make sure the individual images in the sprite have the same height. For the opposite case: when you want to repeat horizontally, sprite vertically.
Example
» Demo
You have three divs and you want to repeat their background vertically, so that the background takes the whole height of the div, according to the content.
Source images:
Singe image sprite:
![]()
CSS definitions to make this work:
div { background-image:url(sprite8.png); background-repeat: repeat-y; width: 160px; padding: 20px; margin: 20px; float: left; } #my { background-position: 0px; } #my2 { background-position: -200px; } #my3 { background-position: -400px; }
Every image is 200px wide. Because of the 2x20px margin left and right, the width is 160px (=200 - 20 - 20)
The tree divs have IDs: my, my2, my3
Result
Once again, the result
Tested on Windows with IE7, FF, O, S.




April 8th, 2008 at 1:07 am
Nice to see this issue addressed, thanks… I like to use percentage widths though–I guess only something like SVG would allow one to indicate a percentage width/height which would work on both the image as well as the containing element?
April 15th, 2008 at 1:49 am
[...] comentarios de esta entrada suscribiendote al feed RSS 2.0. Puedes dejar un comentario, o enviar un trackback desde tusitio. [...]
June 17th, 2008 at 2:18 am
css background examples , Properties , Attribute - - http://css-lessons.ucoz.com/background-css-examples.htm
October 24th, 2008 at 7:11 am
Thanks for the demo and the special instruction on repeating css sprite images!