Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Igor Kałużny
Igor Kałużny
4,337 Points

scalable div with background-image

Hello, I can't set a div to scale with changing window size. The img is set to cover, but when I change the div size to auto or a % value it disappears. It is only visible when the height is set to px but then it's not scalable.

 </header>
    <div id="banner">
    </div>
#banner {
  background: blue url('../img/aps.jpeg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  width: 100%;
  height: (%) - (disappears) height: (px)   (not scalable)
Jake Salo
Jake Salo
13,175 Points

Would you mind showing us some code? It would make it easier to help you.

2 Answers

Andrew Shook
Andrew Shook
31,709 Points

try giving you container a padding bottom in percent.

#banner {
  background: blue url('../img/aps.jpeg');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  width: 100%;
  padding-bottom: 16%;
}

play around with that percentage to see what fits best for you. The only downside to this approach is that you may end up with blank spaces to the side depending on the dimensions of the window. To the best of my knowledge there really isn't anything you can do about this. I usually just hide images like these for mobile and possibly tablets in landscape mode. I just depends on what looks good at that point.

Igor Kałużny
Igor Kałużny
4,337 Points

I'm not sure how does it work, but it does. Thank you ;)

Andrew Shook
Andrew Shook
31,709 Points

From the css box model spec:

The percentage is calculated with respect to the width of the generated box's containing block.

You can find the spec here. You should note that this also applies to margins as well. The real trick is find out the ratio of the height and width of your image. So if your image 2000px tall and 4000px width (never use pictures this big, I'm just using these numbers as an example) then the ratio would be 1:2. That means you would want to set the padding bottom property to roughly 45% to 49%. I alway recommend using slightly less than the actual ratio so that you don't get white space on the top, bottom, or sides. Of course, if your background is white it may not matter.