div overlaying image at large screen size not stacking as screen shrinks

Apologies for the poor title, my terminology is weak but I am working on it.

I have a div partially covering a background image when the screen width is at a larger size. For smaller screen widths, I would like that div to drop below the background image rather than continue to overlay the background image—as what currently I have here in this pen:

https://codepen.io/Ywehc/pen/KQqQeN

<div class="container-fluid" style="width:cover">
    <img src="https://images.unsplash.com/photo-1490641525855-f5ffa411459d?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=85bad8135a13687bbd2ac661023e8dc4&auto=format&fit=crop&w=1189&q=80" style="width:100%">
  <div class="overlaid-div" style="background-color: blue; height: 15em; width: 20em; margin-left:50%; margin-top: -100px; position: relative">
  </div>
  <div class="randomelement" style="width: 30em; height:10em; background-color: black">
  </div>
</div>

So basically I would like to keep overlay for large screen widths, but as screen width went smaller, the divs should stack vertically and the blue div should not overlay anymore.

Thank you kindly!

2 answers

  • answered 2018-02-13 02:21 AKZhang

    add this to css. You should use @media to change the margin based on desired screen size

    @media only screen and (min-width:400px){ // Change 400px to your desired the maximum of smallest width screen
      .overlaid-div {
        margin-top: 0%
      }
    }  
    @media only screen and (min-width:1000px){
      .overlaid-div {
        margin-top: -10%
      }
    }  
    

    and, delete margin-top from inner style

  • answered 2018-02-13 02:21 Andy Hoffman

    You only need a single media query to achieve this (adjust break-point width as necessary).

    @media only screen and (max-width: 700px) {
      .overlaid-div {
        /* !important is needed to override your inline margin style */
        margin-top: 0 !important;
      } 
    }
    

    https://codepen.io/antibland/pen/XZgEzo