0

I have the following structure;

<body>
    <div id="splash">
      <img /> <!-- 512x512 -->
      <progress></progress>
      <img /> <!-- 512x512 -->
    </div>
</body>

And this css;

html, body {
    height: 100%;
}

#splash {
    max-height: 100%; /* does nothing */
}

#splash img {
    max-width: 100%;
    height: auto;
}

This results in the entire div scrolling to fit within the width of the browser window. Currently this also scales the div in height, pushing the contents below the bottom bounds of the browser window.

Is it possible to also scale the div vertically such that its contents shrink so no part of it drops below the bottom bound of the browser window?

fiddle

Stafford Williams
  • 9,696
  • 8
  • 50
  • 101

3 Answers3

1

body { 
    margin: 0;                /* 1 */
}

#splash { 
    height: 100vh;
    display: flex;            /* 2 */
    flex-direction: column;   /* 2 */
}

#splash > img {
    min-height: 0;            /* 3 */
    object-fit: contain;      /* 4  (also try `cover` value) */
    width: 100%;
}

progress {
    width: 100%;
}
<div id="splash">
    <img src="http://lorempixel.com/512/512/" />
    <progress></progress>
    <img src="http://lorempixel.com/512/512/" />
</div>

jsFiddle

Notes:

  1. Remove default margins on body element (which can cause scrollbars)
  2. Establish vertical flex container
  3. Enable flex items to shrink past content size
  4. Force images to respect aspect ratio (Note that object-fit is not yet supported by IE and Edge. For workaround options see here).
Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
1

Your percentages don't work because html does not have a defined height. Use 100% too.

html, body, #splash {
  height: 100%;
  margin: 0;
}
#splash img {
  max-height: 48%;
  display: block;
  margin: 0 auto;
}
progress {
  display: block;
  box-sizing: border-box;
  width: 100%;
  height: 4%;
}
<div id="splash">
  <img src="http://lorempixel.com/512/512/" />
  <progress></progress>
  <img src="http://lorempixel.com/512/512/" />
</div>

You can achieve more flexibility using calc() or flexbox.

Oriol
  • 274,082
  • 63
  • 437
  • 513
1

Michael_B's answer pointed me in the right direction, however I ended up going with something that doesn't rely on object-fit being supported.

It required adding a surrounding div to the progress, and limiting the height of the images to an estimate of the space I expect them to take up, in this example, 45%.

jsfiddle

html, body {
  height: 100%; 
  width: 100%;
  margin: 0;
}

#splash {
  height: 100%;
}

#splash img {
  max-width: 100%;
  max-height: 45%;
  width: auto;
}
<div id="splash">
    <img src="http://lorempixel.com/512/512/" />
    <div>
      <progress></progress>
    </div>
    <img src="http://lorempixel.com/512/512/" />
 </div>
Stafford Williams
  • 9,696
  • 8
  • 50
  • 101