align-items: center makes img disappear

Viewed 2615

So with the grid, when I don't have align-items: center; the img shows fine, but once I add align-items: center; it suddenly disappears. What's causing this issue?

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  height: 100px;
}

img {
  display: block;
  max-height: 100%;
  margin: 0 auto;
}

.align {
  align-items: center;
}
<div class="grid">
  <div>
    <span>text</span>
  </div>
  <div>
    <img src="http://via.placeholder.com/650x1050" />
  </div>
</div>

<div class="grid align">
  <div>
    <span>text</span>
  </div>
  <div>
    <img src="http://via.placeholder.com/650x1050" />
  </div>
</div>

This seems to be a Chrome issue. It's also not fitting the img properly on firefox.

1 Answers

This happens because of the way percentage heights are rendered in the browser.

When align-items: center is not present, align-items: stretch (the default value) is in effect. This automatically gives the flex item (the div) full height.

But when align-items: center is present, it vertically centers the div. The child of the div, the img with max-height: 100%, actually computes to height: auto, because there is no height reference on the parent (the div flex items).

The problem is resolved by setting a height on the flex items.

.grid > div {
  height: 100%;
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  height: 100px;
  border: 1px solid red;
}

.grid>div {
  height: 100%;
}

img {
  display: block;
  max-height: 100%;
  margin: 0 auto;
}

.align {
  align-items: center;
}
<div class="grid">
  <div>
    <span>text</span>
  </div>
  <div>
    <img src="http://via.placeholder.com/650x1050" />
  </div>
</div>
<br><br>
<div class="grid align">
  <div>
    <span>text</span>
  </div>
  <div>
    <img src="http://via.placeholder.com/650x1050" />
  </div>
</div>

More details here:

Related