Search code examples
htmlcssbackground-imagebackground-color

How can I display a background image on top of background color?


I want to display a background image on top of background colors. The difficulty is that the background image must be over two boxes and must not be cut between boxes. I found a way to display the image over the color by defining the background image in each box, but it cuts the image.

Here is my original code where the background color is above the background image and hides it:

.wrapper {
  background-image: url(https://i.ibb.co/gD7vNSs/fleur-cerf.png), url(https://i.ibb.co/Nn2Wt9Q/fleur-renard.png);
  background-position: top left, top right;
  background-repeat: repeat-y; 
}
.box1 {
    padding: 50px;
    padding-left: 100px;
    background: #f6f7f9;
}

.box2 {
    padding: 50px;
    padding-left: 100px;
    background: #e89d8c;
}
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
  <div class="wrapper">
    <div class="box1">
     <h1>This is a heading</h1>
     <p>
     This is paragraph
     </p>
   </div>
   <div class="box2">
     <h1>This is a heading</h1>
     <p>
     This is paragraph
     </p>
    </div>
  </div>
</body>
</html> 

Any idea?


Solution

  • A pseudo element and few z-index can do it:

    .wrapper {
      position:relative;
    }
    
    .wrapper::after {
      content:"";
      position:absolute;
      top:0;
      left:0;
      right:0;
      bottom:0;
      background-image: url(https://i.ibb.co/gD7vNSs/fleur-cerf.png), url(https://i.ibb.co/Nn2Wt9Q/fleur-renard.png);
      background-position: top left, top right;
      background-repeat: repeat-y;
    }
    
    .box1 {
      padding: 50px;
      padding-left: 100px;
      background: #f6f7f9;
    }
    
    .box2 {
      padding: 50px;
      padding-left: 100px;
      background: #e89d8c;
    }
    /* to make the content always on the top */
    .box1 *,
    .box2 * {
      position:relative;
      z-index:2;
    }
    <div class="wrapper">
      <div class="box1">
        <h1>This is a heading</h1>
        <p>
          This is paragraph
        </p>
      </div>
      <div class="box2">
        <h1>This is a heading</h1>
        <p>
          This is paragraph
        </p>
      </div>
    </div>