Search code examples
htmlcssbackground-image

css background-image to continue from a div to another


I'm looking for a way to have a png background image (with transparency) to start a first div (with colored background) and to continue in the next div but where it stopped from the previous div.

Let's say we have this structure :

<section>
   <div id="1">some text</div> <!-- background-image starts at the top and ends at the end -->
   <div id="2">some text</div> <!-- same background-image starts where it ended in #1 -->
</section>

but div #1 and #2 have colored background. We can have colored background AND background-image but I need to make sure the background image starts in div#2 where it stopped it div#1 and it has to be responsive of course.

I can't use background-image on section because DIVs have colored background and that will hide the background-image from section.

The goal is to use CSS only, but if the only way is to use javascript/jquery, why not. The problem if I use simple background-image on #1 and #2 is that the image will cut itself at the end of #1 and starts again at #2. And I can't use another absolute div because I need to be able to select the text or click the buttons in the DIVs

Here is an image to illustrate the idea.

  • div#1 is filled with yellow, #2 is red.
  • background-image is the green triangles with transparent background, just the triangles.
  • you can see that the last triangles that are at the bottom of #1 would continue in #2.

enter image description here


Solution

  • You could use an absolutely positioned pseudo element to host the background image, though it would require another level of nested elements.

    section {
      position: relative;
    }
    
    section::before {
      content: "";
      background: url(https://placehold.it/100x100) repeat;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      opacity: .5;
    }
    
    section > div > div {
      position: relative; /* Pull the content above the ::before */
    }
    
    section > div:nth-child(1) {
      background: red;
      height: 200px;
    }
    
    section > div:nth-child(2) {
      background: yellow;
      height: 300px;
    }
    <section>
       <div id="1">
         <div>
           some text
         </div>
       </div>
       <div id="2">
         <div>
           some text
         </div>
       </div>
    </section>