9

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.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
A. L
  • 11,695
  • 23
  • 85
  • 163

1 Answers1

10

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:

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • hmm, but the text no longer centers, which was my original intention of using `align-items: center`. I guess I'll just have to use position absolute on the `span` then. But this answers the question. – A. L Nov 14 '17 at 00:43
  • No need for absolute positioning. This works in Chrome and Firefox: https://jsfiddle.net/yzoj5f8f/6/ – Michael Benjamin Nov 14 '17 at 01:13