vicatcu
vicatcu

Reputation: 5837

CSS x-repeating background avoid undesirable truncation

I've got a horizontally repeating divider background image that looks like this:

enter image description here

.divider {
    background-image: url('https://i.sstatic.net/kMCJ6.png');
    background-repeat: repeat-x;
    height: 200px;
    width: 100%;
    display:block;
}
<div class="divider"></div>

Inevitably though, based on the width of the browser window I can end up with a rendering that looks like this:

enter image description here

Is there any way to ensure that the horizontal repetition breaks only through white space in the background image? That is to say, is there a way to use CSS (and maybe some Javascript) to specify something like, don't repeat a copy of the background image unless you can fit the whole repeating tile in the visible area?

Upvotes: 2

Views: 30

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42314

If you are willing to have spaces between the repeating images, you can use
background-repeat: space:

.divider {
  background-image: url('https://i.sstatic.net/kMCJ6.png');
  background-repeat: space no-repeat;
  height: 200px;
  width: 100%;
  display: block;
}
<div class="divider"></div>

Alternatively, you can scale the image to fit with background-repeat: round:

.divider {
  background-image: url('https://i.sstatic.net/kMCJ6.png');
  background-repeat: round no-repeat;
  height: 200px;
  width: 100%;
  display: block;
}
<div class="divider"></div>

Note that both space and round apply the repetition both horizontally and vertically by default, so if you only want to apply the repetition horizontally, you can pass no-repeat as the second parameter (as seen above).

Upvotes: 2

Related Questions