Search code examples
htmlcssresponsive-designmedia-queriesbackground-image

Using image as background in empty div to cover entire area in a responsive web app


I've seen many topics similar to this one, but nothing has worked so far and they don't quite fit my needs.

I have a responsive web app, which is expected to be used on wide screens and on the smallest mobile devices. A part of the screen needs to be 100% covered by an image for all device sizes (to which the image needs to resize accordingly), while the other has some text content, buttons, etc.

The best way to approach this is with two divs, one has the image, the other the content. Like this:

<div>
  <div class="left">
    <!-- Dont want to put anything here, just background img -->
  </div>
  <div class="right">
    <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit....
    </p>
    <button>Do something</button>
  </div>
</div>

Unfortunately I can't get this to work with my div having the background image. I either have to preset the width and height or I need to content in that div, at which point the image only covers as much as the content.

So, my question is how do I get to fill the div to be responsive and always display that background image.

Here is the full code of what I already have

I do understand that I can simply set the height of my class and I'll have something, so basically this:

.left {
    float: left;
    background-image: url('https://static.pexels.com/photos/20787/pexels-photo.jpg');
    background-size: cover;
    background-repeat: no-repeat;
background-attachment: auto;
    max-width: 100%;
    height: 1000px;
}

But I want to make sure, the screen stays responsive and adapts depending on the sizes, so hard coding the value doesn't make sense.

Edit: as requested, added a mockup in case someone needs it. The left would be a larger screen such as a monitor, while the right would be a small, mobile device's screen: enter image description here


Solution

  • On the .left div use following CSS:

    position: fixed;
    width: 100vw;
    height: 100vh;
    z-index: -999;
    top: 0;
    left: 0;
    

    And delete the max-width.