panthro panthro - 6 months ago 12
CSS Question

Make image take full height of flex item

I have a container that is 100vh (minus the fixed nav height).

<section class="container">


Inside this container I have some text:

<div class="text">
<p>title</p>
</div>


Which can be of any length as the content is dynamic.

Below this text I have an image:

<div class="image">
<img src="https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg">
</div>


The image needs to fill the rest of the 100vh (- nav height) container.

I use:

.container{
display:flex;
flex-flow: column nowrap;
....


Fiddle

The issue I am having is that I need the image to be the height of the rest of the space.

How can I do this? In my fiddle, if your screen is small it is being cut off and if your screen is large it does not fill the space. Height: 100% fails to work, making it too large.

Flex solutions only please, no table tricks - thanks!

Answer

Make the image container (.image) a flex container with height: 100%.

You can then fine-tune the aspect ratio and alignment with object-fit and object-position.

nav {
    position:fixed;
    background:grey;
    width:100%;
    height: 100px;
}

main {
  padding-top: 100px;
}

.container {
    display:flex;
    flex-flow: column nowrap;
    height: calc(100vh - 100px);
    background: green;
    border: 3px solid brown;
}

.text { background: yellow; }


/* ***** NEW ***** */
.image {
  display: flex;
  justify-content: center;
  height: 100%;
} 
img {
  width: 100%;
  object-fit: contain;
}
<nav>Nav</nav>
<main>
    <section class="container">
        <div class="text"><p>title</p></div>
        <div class="image">
            <img src="https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg">
        </div>
    </section>
    <section class="container">
        <div class="text"><p>hello</p></div>
        <div class="image">
            <img src="https://s-media-cache-ak0.pinimg.com/736x/d1/a6/64/d1a664bca214bf785a293cbc87950fc4.jpg">
        </div>
    </section>
</main>

Revised Fiddle

Note that the object-fit property is not supported by IE. For more details and a workaround see: http://stackoverflow.com/a/37127590/3597276