Reputation: 1336
I am trying to prevent an image from extending outside the border of a grid item that has a height set of 0 and padding-top of 100% to maintain a 1:1 aspect ratio. It works fine when using an <img>
element (on the left), but not a <picture>
element (on the right).
.grid {
display: grid;
grid-template-columns: 1fr 1fr
}
.item {
display: block;
position: relative;
padding-top: 100%;
height: 0;
background-color: grey;
border: 1px solid black;
}
.inner {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: grid;
grid-template-rows: minmax(20px, 1fr) auto auto minmax(20px, 1fr);
}
.text {
grid-row-start: 2;
text-align: center;
margin-top: 0;
margin-bottom: 15px;
}
.img {
grid-row-start: 3;
max-height: 100%;
width: auto;
max-width: 100%;
display: block;
margin-left: auto;
margin-right: auto;
}
<ul class="grid">
<li class="item">
<div class="inner">
<p class="text">Text</p>
<img class="img" src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />
</div>
</li>
<li class="item">
<div class="inner">
<p class="text">Text</p>
<picture class="img">
<source srcset="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80 1x, https://images.unsplash.com/photo-1618236507249-9960f2c6a53d?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80 2x"
media="(min-width: 360px)">
<img src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />
</picture>
</div>
</li>
</ul>
Upvotes: 2
Views: 347
Reputation: 2800
Put a class to the img as well.
<img src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />
to
<img class="img" src="https://images.unsplash.com/photo-1621250755294-57cf625b4a9a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" />
Add overflow: auto to class img
Upvotes: 1