Background Repeat and its Possibilities

There is a humble CSS Property that gets overlooked a lot, the humble background-repeat.

I recently only learned that there a few options other than no-repeat or repeat available to this, and that they have really good browser support.

New Keywords

There are two CSS level 3 specification additions to the background-repeat property - space and round.

space

background-repeat: space;

With a repeating background image, using this keyword will repeat the image as many times as it can without clipping the image. Much like flexbox and justify-content: space-between, it will distribute the remaining space between the items that fit. The images in the background will stay their original size (or the one specified by background-size).

Note - if you use the space value, for the most part a background-position declaration will be ignored.

round

background-repeat: round;

I think this value is even more interesting, because what it does is actually scales the repeated image such that all available room is taken up, until there is enough room for another instance of the image.

In the below example I’ve added an SVG background image with a border to illustrate how the image will scale up until another can fit, then they all scale down again:

Older Keywords

Just in case you didn’t know the other keywords, they are:

background-repeat: repeat;

This is the default for background images - they will repeat in a tile-like fashion in both dimensions.

background-repeat: repeat-x; /* repeats horizontally */
background-repeat: repeat-y; /* repeats vertically */

If you only want a background to repeat in one direction, use these.

background-repeat: no-repeat;

If you don’t want any repetition at all.

And it supports these global values:

background-repeat: inherit;
background-repeat: initial;
background-repeat: unset;

Two Value Syntax

You can also specify separate repeat rules in two dimensions with the two value syntax:

background-repeat: horizontal-keyword vertical-keyword;

So you could have:

background-repeat: repeat space;

See how the background tile clips because we use repeat in the horizontal dimension?

Multiple Background Images

You can even manipulate background-repeat for multiple background images, so each follows different rules.

background-image: url(path/to/image_1), url(path/to/image_2);
background-repeat: round round /* image_1 */, space no-repeat /*  image_2 */;

So, take a fresh look at background-repeat - it can provide a lot of opportunities for happy discoveries.

comments powered by Disqus