Search code examples
htmlcssgoogle-chromeflexboxinternet-explorer-11

Maintain image aspect ratio in nested flexbox container on IE11


I'm using flexbox to display a row of blocks. Each block is using flexbox to display a column of elements. One of the elements is an image that needs to maintain its aspect ratio. The code below is a simplified version of my code that illustrates what I'm trying to do.

In Chrome the images scale to 186px x 186px. In IE11 they display 186px x 500px. I've tried wrapping the images in another div and setting its height and/or width to 100%, but nothing works for both Chrome and IE11.

section {
    max-width: 600px;
    margin: 0 auto;
}

.grid {
    display: flex;
    flex-wrap: wrap;
    margin-left: -20px;
    margin-top: 10px;
}

.block {
    margin: 0;
    flex: 1 0 150px;
    margin-left: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.block img {
    width: 100%;
}
<section>
    <div class="grid">
        <div class="block">
            <img src="http://placehold.it/500" alt="">
            <h2>Block title</h2>
        </div>
        <div class="block">
            <img src="http://placehold.it/500" alt="">
            <h2>Block title</h2>
        </div>
        <div class="block">
            <img src="http://placehold.it/500" alt="">
            <h2>Block title</h2>
        </div>
    </div>
</section>


Solution

  • It looks like adding min-height: 1px; to the img is the solution. I wish I had a good explanation for why this works. Here's the best I could find:

    ... My best guess is that the min-height forces IE to recalculate the height of the rendered content after all of the resizing, and that makes it realize that the height is different....