-1

I've been trying to limit the height of a DIV so that it is never taller than the browser window but it just isn't working. Here's a copy of the relevant HTML/CSS that you can just paste into a file to try:

.imageContainer1 {
  display: block;
  width: 100%;
  height: 100%;
}
.imageContainer2 {
  display: inline-block;
  width: 100%;
  height: 0;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
  padding: 75% 0 0 0;
  background: url("https://dancing.moe/frames/jpg/1.jpg") no-repeat;
  background-size: 100% 100%;
}
<div class="imageContainer1">
  <div class="imageContainer2">
  </div>
</div>

The padding is to maintain an aspect ratio of 4:3. Everything's a bit out of whack since I've basically mashed together many examples.

Any ideas as to why this just won't work? Even specifying in pixels doesn't affect the child.

Kaii
  • 20,122
  • 3
  • 38
  • 60
spacer GIF
  • 626
  • 5
  • 19
  • how would your result look like?Can you describe the behavior? – helle Dec 29 '16 at 18:56
  • Do you mean you'd like the image to fill the `
    ` height at 100% in any browser window?
    – justDan Dec 29 '16 at 19:01
  • Something like this? https://jsfiddle.net/hka2fncj/. Use the cursor to grow or shrink the div height and the image will remain at 100% height. Sorry if I'm not getting this right. – justDan Dec 29 '16 at 19:02
  • Why aren't you using an `img` tag? – André Dion Dec 29 '16 at 19:05
  • check this https://jsfiddle.net/2n4f6cuu/. you need to specify the height or assign it programmatically with javascript or jquery. – Sachin Kadam Dec 29 '16 at 19:07
  • You'd use an `img` tag to display an image for proper semantics (e.g., screen readers, printing, crawlers), not `background-image`. That aside, it's still not clear what output you're after exactly. – André Dion Dec 29 '16 at 19:12

2 Answers2

0

Just use a height measured in vh. I also removed your padding, etc.

.imageContainer1 {
  display: block;
  width: 100%;
  height: 100%;
}
.imageContainer2 {
  display: block;
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
  background: url("https://dancing.moe/frames/jpg/1.jpg") no-repeat;
}
<div class="imageContainer1">
  <div class="imageContainer2">
  </div>
</div>
Serg Chernata
  • 12,280
  • 6
  • 32
  • 50
0

Is this what you are looking for?

The key in this solution is background-size: contain, which keep the image's aspect ratio while show the image in full without cropping it

html, body {
  margin: 0;
}
.imageContainer1 {
  height: 100vh;
  background: url("https://dancing.moe/frames/jpg/1.jpg") no-repeat center center;
  background-size: contain;
}
<div class="imageContainer1">
</div>

And if you need to use other elements inside, behaving in a similar way, check this post, it is a really good one: scale-element-proportional-to-background-cover-and-contain

Community
  • 1
  • 1
Asons
  • 84,923
  • 12
  • 110
  • 165