Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 542
Todd Avatar asked Mar 22 '18 18:03

Todd


2 Answers

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....

like image 165
Todd Avatar answered Nov 18 '22 11:11

Todd


Fellow stranger looking for fix, but featured on top answer didn't help. Setting min-width: 1px; to the img may help you as well.

like image 30
Yakovonthego Avatar answered Nov 18 '22 11:11

Yakovonthego