How to contain an image within a fixed height flexbox with flex grow

Published February 11, 2021 (2 min read)

A css solution to containing an image within a flex grow container with a fixed height flexbox without extending the size of the container.

I wanted to create an image preview modal that adjusted to the viewport with a variable header and footer, with the image no matter what size fitting within the remaining space. I was using `flexbox` with `flex-grow` to keep the footer at the bottom of the page so the image stays in the center.

The effect I was looking for was similar to that of an image being opened in a new tab, so the modal would fill the whole viewport and I just wanted the image to keep it's proportions and fill the remaining space in the container. However if the image was too large it would extend the height of the container, push the footer off the page and ruin the effect. To stop this from happening I found this trick:

overflow: auto;

Setting this to the container with flex-grow fixed all my issues, now I had a responsive image preview modal with an adjustable header and footer contained within my window. Check out the working codepen below.

See the Pen Image fill remaining height of container with flexbox by epndavis (@epndavis) on CodePen.