Search code examples
htmlcsstwitter-bootstrapbackground-image

Get background image to overlap another background image between two <div> Elements


I have the following HTML(Bootstrap) (really broken down, should be enough though):

<div class="container-fluid" id="hero">
    <div class="container container-padding">
        <div class="row">
            <div class="col" align="center">

            </div>
        </div>
   </div>
</div>
<div class="container-fluid" id="spotlight">
    <div class="container container-padding">
        <div class="row">
            <div class="col" align="center">
                <img src="img/spotlight.png" />
            </div>
        </div>
    </div>
</div>

And I am using a background image on each "container-fluid" element.

Now I need the first background Image overlap the second "container-fluid".

However when I use negative margins on both of the e.g (margin-top:-50px or margin-bottom:-50px - it appears that always the second overlaps the first.

I tried z-index which wouldn't work for background-images. I can't really include the second background image as an actual image because I want to add content to that element.

How do I get the first div overlap the second when using negative margins?

Would appreciate any help, thanks!


Solution

  • Just use the position other than static and control them via z-index:

    .container-fluid {
    	position: relative;
    	min-height: 50px;
    }
    
    #hero {
    	background: url('https://via.placeholder.com/350x150/ff0000') no-repeat;
    	background-size: cover;
    	z-index: 10;
    	top: 20px;
    }
    
    #spotlight {
    	background: url('https://via.placeholder.com/250x250/00ff00') no-repeat;
    	background-size: cover;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
    
    <div class="container-fluid" id="hero">
        <div class="container container-padding">
            <div class="row">
                <div class="col" align="center">
    
                </div>
            </div>
       </div>
    </div>
    <div class="container-fluid" id="spotlight">
        <div class="container container-padding">
            <div class="row">
                <div class="col" align="center">
                    
                </div>
            </div>
        </div>
    </div>

    Playground.