How to make a background image responsive in CSS

user3642210 picture user3642210 · Aug 16, 2016 · Viewed 10.4k times · Source

I asked a question previously on getting 2 divs to sit inside another div bootstrap container (1 top left, and 1 bottom right) which has now been solved.

My next issue is, in the main div (with 2 divs sitting inside) I need a large background image, which is responsive, so brings the bottom right div upwards and inwards as the browser is made smaller.

Here is what I have so far:

<style>
#header {
background-image: url(/images/background-image.jpg);
position: relative;
}

#header .container {
height: 893px;
position: relative;
}

#header .div1 {
position: absolute;
top: 20px;
}

#header .div2 {
position: absolute;
bottom: 20px;
right: 20px;
}

<div id="header">
<div class="container">
    <div class="div1">
        Top left content
    </div>
    <div class="div2">
        Bottom right content
    </div>
</div>

Adding the background image to the CSS like how I have done above, does not make the image responsive, but if I add it to the HTML as an image I cannot get the divs to sit on top of the image.

What is the correct method of doing this?

Answer

Steven Ventimiglia picture Steven Ventimiglia · Aug 16, 2016

With a few cross-browser vendor prefixes.

#header {
    display: block;
    position: relative;
    background: url('/images/background-image.jpg') 50% 0 no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}