I\'m trying to figure out how to make a background-image in a div full width and responsive. The background-image is expanding across the width of the page (and is responsive),
Here is one way of getting the design that you want.
Start with the following HTML:
This is centered text.
main area
Note that the background image is now part of the regular flow of the document.
Apply the following CSS:
.bg-image {
position: relative;
}
.bg-image img {
display: block;
width: 100%;
max-width: 1200px; /* corresponds to max height of 450px */
margin: 0 auto;
}
.bg-image h1 {
position: absolute;
text-align: center;
bottom: 0;
left: 0;
right: 0;
color: white;
}
.nav, .main {
background-color: #f6f6f6;
text-align: center;
}
The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block
and margin: 0 auto
.
The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1
element to be the full width of the parent and use text-align: center
to center the text. Use the top or bottom offsets to place the text where it is needed.
If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img
dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.
See demo at: http://jsfiddle.net/audetwebdesign/EGgaN/