Search code examples
cssbackground-image

How to prevent background repeat image from cutting off


Is there a way to prevent css from cutting off a background image using background repeat? background-repeat: repeat-x; repeats the image side by side until the space runs out, and cuts the image where the div finishes. Is there a way to space the images between instead? like a sort of justify-content: space-between; but for background images?

current result

enter image description here

expected result

enter image description here

I know I can use images and use display flex, but this would mess with the layout. I also read this SO question where it shows how to do it with js but I think this is not worth it as I'd have to listen to the resize event to make it responsive. Is there a way to do it with just css?

#container {
  width: 250px;
  height: 100px;
  background-image: url('https://placekitten.com/100/100');
  border: black solid 3px;
}
<div id="container">
</div>

`


Solution

  • You can use background-repeat: space;

    https://developer.mozilla.org/en-US/docs/Web/CSS/background-repeat

    #container {
      width: 250px;
      height: 100px;
      background-image: url('https://placekitten.com/100/100');
      border: black solid 3px;
      background-repeat: space;
    }
    <div id="container">
    </div>