John Doe John Doe - 1 year ago 47
CSS Question

How to make div's height AND background image stretch to wrap around all content in the div?

I while ago while making a site, I didn't set a height for a div section and filled it with content. Then I set the background-image to an image, and the image/div stretches to wrap the content since there is no height. I have been trying to replicate it but every time I do the same thing, the background image disappears but the content is still there (white text, can't see unless selected). This happens when I set it like:

background-image: url("images/pizza-dark.jpg");
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
clear: both;

I know there is a way to do this but I'm not quite sure. This is crucial to the site because I am using bootstrap columns and a set height won't give a good result on mobile. In the JSFiddle below, there is no set height and, as you can see, the background image doesnt show at all. Even if you set it to 100%, the content that folds down (coloumns from Bootstrap) wont show since the background image doesnt stretch that far.. I have tried height:auto too and that doesn't work either.

Here is a JS Fiddle:


Answer Source

You forgot to add float property to main container. You can use vh units for the main container height, and it will fits to every screen size:

#main {
background-image: url("    content/uploads/2015/09/4791207-9790062099-Pizza1.jpg");
background-repeat: no-repeat; 
background-size: cover;
float: left;
width: 100%;
height: 100vh;

Here is a fiddle: fiddle link