简体   繁体   中英

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:

#main{
    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: https://jsfiddle.net/du53n862/

Thanks!

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("http://itspizzatime.ca/wp-    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

I'm not sure if this is the behavior you want, but if you add a height of 100% and a scrolling overflow to your main div, the image will just be a fixed full-cover image in the background. This seems to be working fine in this fiddle .

#main {
  height: 100%;
  overflow: scroll;
  ...
}

This issue can easily be solved with flexbox. If you can drop support of older browsers here is the simple solution https://jsfiddle.net/1p1k41ot/ .

I just added few lines in #main

#main {
...
display: flex;
flex: 1 1;
height: 100%;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM