New Repeating Background Image Options in CSS3

Craig Buckler
Share

In CSS2.1, the background-repeat property had four options: no-repeat, repeat, repeat-x and repeat-y. While these are undoubtedly useful, they don’t permit finer control over the repeating process and tiles will be clipped if they don’t fit the container an exact number of times.

CSS3 introduces two new options: space and round

background-repeat: space

The space option will repeat a tile horizontally and vertically without clipping or resizing the or image, e.g.


background-repeat: space;

background repeat space

background-repeat: round

The round option will repeat a tile horizontally and vertically without clipping, but the image may be resized, e.g.


background-repeat: round;

background repeat round

Assume we have a background image with a width 100px (actual or resized using the CSS3 background-size property). This is contained in an element with 520 horizontal pixels, so:

round(520 / 100) = round(5.2) = 5

The browser will render five images in the space but adjust the image width to 104px (520px / 5). The image is made wider to fit the container.

Differing Horizontal and Vertical Repeats

background-repeat can be passed two values to alter the horizontal and vertical repeating, e.g.


background-repeat: round space; /* width resizes, height static */
background-repeat: space round; /* width static, height resizes */
background-repeat: space no-repeat; /* fit tiles horizontally only */

Changing the Background Position

Tiling with space or round will only work as you expect if the background-position is set to 0 0. You are free to change it; the image sizes and spacing will be tiled the same but the top-left offset is moved accordingly.

Browser Compatibility

Two browsers support the space and round properties. Guess which ones? You’re wrong: it’s IE9 and Opera. At the time of writing, they are not implemented in Firefox, Chrome or Safari. It gets worse:

  • When Firefox encounters space or round it falls back to repeat.
  • When Chrome or Safari encounter space or round they fall back to no-repeat. In addition, the webkit browsers appear to recognize the properties but don’t render them correctly.

Great. Thanks guys.

The only way to achieve any sort of consistency is to force Firefox to render like webkit, e.g.


#element
{
	background-repeat: no-repeat;
	background-repeat: space;
}

Therefore:

  • IE9 and Opera will correctly repeat a tile horizontally and vertically without clipping or resizing the image.
  • Firefox won’t recognize space, falls back to the no-repeat setting and shows a single tile.
  • Chrome and Safari recognize space but incorrectly show a single, non-repeated title.

Nasty. It might be best to wait a few more months until Mozilla and Webkit add full support for CSS3 background-repeat.

View the CSS3 background-repeat demonstration page…