我有一个简单的CSS网格,有两列(60%,40%(。第一个是一张图片。当图片有足够的高度时,它就很好地包含在网格中。
问题是当它没有足够的高度时,图片的高度就会溢出
我希望它保持在网格内,并填充它,无论窗口大小。
这是代码:
.container {
display: grid;
grid-template-columns: 60% 40%;
height: 100vh;
border: 2px solid red;
}
.picture {
width: 100%;
height: 100%;
object-fit: cover;
}
<div class="container">
<img class="picture" src="https://i.pinimg.com/550x/e4/7e/00/e47e006f1cf838ccf5468e8548a7577c.jpg">
<p class="text">Some text</p>
</div>
这是一个JSFiddle:https://jsfiddle.net/f4us5krq/1/
您可以将容器上的高度设置为100%,这样图片就可以放在里面了。如果您仍然想使用height: 100vh;
,可以在.picture上尝试overflow: hidden;
.container {
display: grid;
grid-template-columns: 60% 40%;
height: 100vh;
border: 2px solid red;
}
.picture {
width: 100%;
height: 100%;
object-fit: cover;
overflow: hidden;
}
<div class="container">
<img class="picture" src="https://i.pinimg.com/550x/e4/7e/00/e47e006f1cf838ccf5468e8548a7577c.jpg">
<p class="text">Some text</p>
</div>
将width
和height
更改为inherit
。如果网格太紧,添加最大宽度/高度以阻止溢出。
.container {
display: grid;
grid-template-columns: 60% 40%;
height: 100vh;
border: 2px solid red;
}
.picture {
object-fit: cover;
height: inherit;
width: inherit;
max-width: 100%;
max-height: 100%;
}
<div class="container">
<img class="picture" src="https://i.pinimg.com/550x/e4/7e/00/e47e006f1cf838ccf5468e8548a7577c.jpg">
<p class="text">Some text</p>
</div>
p.S您也可以试用object-fit: contain