Elliott Klein
Elliott Klein

Reputation: 1

Two divs dynamically fill viewport height

I'm having trouble trying to style this set up. The #container should be exactly the height of the viewport, the #caption should take as much height as it needs, and the img in #image should fill the remaining height (while maintaining its aspect ratio). Never should the #container exceed the viewport height.

<div id="container">
  <div id="image">
    <img src="my-image.jpg" alt="my-image">
  </div>
  <div id="caption">
    <p>
      Some info about this image.<br>
      Sometimes this could be two lines.<br>
      Maybe even three.
    </p>
  </div>
</div>

Here's an example of how this would work dynamically:

enter image description here

Any suggestions? I've fiddled with flex and tables myself too but no avail, the page always ends up exceeding viewport height.

Upvotes: 0

Views: 180

Answers (1)

dippas
dippas

Reputation: 60573

you can use flexbox for that

and you may need some media queries.

body {
  margin: 0
}
#container {
  display: flex;
  flex-direction: column;
  height: 100vh
}
#caption {
  flex: 1;
  background: red
}
img {
  display: block;
  margin: auto
}
<div id="container">
  <div id="image">
    <img src="//lorempixel.com/300/500" alt="my-image">
  </div>
  <div id="caption">
    <p>
      Some info about this image.
      <br>Sometimes this could be two lines.
      <br>Maybe even three.
      <br>
    </p>
  </div>
</div>

Upvotes: 2

Related Questions