Search code examples
csssassbackground-image

Random tiled background


I do have 5 tiles with the exact same width/height, I want to know if there is a way to set them as the background randomly.

position: relative;
background-image: url(assets/images/bg_tile1.png), url(assets/images/bg_tile2.png), url(assets/images/bg_tile3.png), url(assets/images/bg_tile4.png), url(assets/images/bg_tile5.png);
background-size: auto;
background-repeat: repeat;

This is waht i have so far, how could I repeat them randomly? Like if they are in a grid (random):

1 4 2 1

2 3 4 1

3 1 5 5


Solution

  • You can approximate this using SVG. You build a random pattern that will repeat. It won't be completely random but it's a good approximation.

    Here is an example with a 3x3 pattern:

    svg {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
    }
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <defs>
        <pattern id="bgimg" x="0" y="0" width="300" height="300"  patternUnits="userSpaceOnUse">
          <image xlink:href="https://picsum.photos/id/1055/100/100.jpg" x="0" y="0" height="100" width="100" />
          <image xlink:href="https://picsum.photos/id/1074/100/100.jpg" x="0" y="100" height="100" width="100" />
          <image xlink:href="https://picsum.photos/id/1080/100/100.jpg" x="0" y="200" height="100" width="100" />
          <image xlink:href="https://picsum.photos/id/1074/100/100.jpg" x="100" y="0" height="100" width="100" />
          <image xlink:href="https://picsum.photos/id/1065/100/100.jpg" x="100" y="100" height="100" width="100" />
          <image xlink:href="https://picsum.photos/id/1039/100/100.jpg" x="100" y="200" height="100" width="100" />
          <image xlink:href="https://picsum.photos/id/117/100/100.jpg" x="200" y="0" height="100" width="100" />
          <image xlink:href="https://picsum.photos/id/1024/100/100.jpg" x="200" y="100" height="100" width="100" />
          <image xlink:href="https://picsum.photos/id/1025/100/100.jpg" x="200" y="200" height="100" width="100" />
        </pattern>
      </defs>
      <rect x="0" y="0" width="10000" height="10000" fill="url(#bgimg)" />
    </svg>