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:

  1. 1.png
  2. 2.png
  3. 3.png

Singe image sprite:

sprite8.png

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.

Bookmark and Share

Somewhat related posts

4 Responses to “Background repeat and CSS sprites”

  1. Brett Zamir Says:

    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?

  2. CSS Sprites (y II) » Criterion Says:

    [...] comentarios de esta entrada suscribiendote al feed RSS 2.0. Puedes dejar un comentario, o enviar un trackback desde tusitio. [...]

  3. e devlet Says:

    css background examples , Properties , Attribute - - http://css-lessons.ucoz.com/background-css-examples.htm

  4. Andrew Says:

    Thanks for the demo and the special instruction on repeating css sprite images!

Leave a Reply