我最近已更新为Mac中的Google Chrome Version 72.0.3626.109 (Official Build) (64-bit)
,并且现在正在破裂。
具有位复杂的嵌套标记背后的原因是因为我需要显示位于div
中心的图像的图像分别为不同的大小,但在Square Div中成比例地调整了大小。因此,在更新新的Google Chrome之前,所有这些都可以正常工作。
.g-parent {
width: 150px;
}
.parent {
position: relative;
padding-bottom: 100%;
background-color: gray;
}
.child {
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
padding-bottom: 100%;
}
.my-img {
width: 100%;
height: 100%;
display: block;
-o-object-fit: contain;
object-fit: contain;
}
<div>
<img class="my-img" src="https://dummyimage.com/400x200/000/fff" />
</div>
<h4>Show above image inside below div</h4>
<div class="g-parent">
<div class="parent">
<div class="child">
<img class="my-img" src="https://dummyimage.com/400x200/000/fff" />
</div>
</div>
</div>
不太确定为什么它起作用,因为在这种情况下height:100%
应该失败,因为父容器中没有设置高度。因此,实际行为似乎是正确的行为。
您可以使图像为position:absolute
来解决此问题:
.g-parent {
width: 150px;
}
.parent {
position: relative;
padding-bottom: 100%;
background-color: gray;
}
.child {
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
padding-bottom: 100%;
}
.child > img {
position:absolute;
}
.my-img {
width: 100%;
height: 100%;
display: block;
-o-object-fit: contain;
object-fit: contain;
}
<div>
<img class="my-img" src="https://dummyimage.com/400x200/000/fff" />
</div>
<h4>Show above image inside below div</h4>
<div class="g-parent">
<div class="parent">
<div class="child">
<img class="my-img" src="https://dummyimage.com/400x200/000/fff" />
</div>
</div>
</div>
您还可以使用一个Div简化此:
.g-parent {
width: 150px;
}
.parent {
position: relative;
padding-bottom: 100%;
background-size:contain;
background-position:center;
background-repeat:no-repeat;
background-color: gray;
}
.my-img {
width: 100%;
height: 100%;
display: block;
-o-object-fit: contain;
object-fit: contain;
}
<div>
<img class="my-img" src="https://dummyimage.com/400x200/000/fff" />
</div>
<h4>Show above image inside below div</h4>
<div class="g-parent">
<div class="parent" style="background-image:url(https://dummyimage.com/400x200/000/fff)">
</div>
</div>
.g-parent {
width: 150px;
}
.parent {
position: relative;
padding-bottom: 100%;
background-color: gray;
}
.child {
top: 0;
left: 0;
right: 0;
bottom: 0;
position: absolute;
padding-bottom: 100%;
}
.my-img {
width: 100%;
height: 100%;
display: block;
-o-object-fit: contain;
object-fit: contain;
}
<div>
<img class="my-img" src="https://dummyimage.com/400x200/000/fff" />
</div>
<h4>Show above image inside below div</h4>
<div class="g-parent">
<div class="parent">
<div class="child">
<img class="my-img" src="https://dummyimage.com/400x200/000/fff" />
</div>
</div>
</div>