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.
To center an image using text-align: center; you must place the <img> inside of a block-level element such as a div . Since the text-align property only applies to block-level elements, you place text-align: center; on the wrapping block-level element to achieve a horizontally centered <img> .
Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
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:
height
property and percentage valuesIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With