【问题标题】:CSS Grid: Picture overflow in height [duplicate]CSS Grid:图片高度溢出[重复]
【发布时间】:2022-01-23 21:13:43
【问题描述】:

我有一个包含 2 列(60%、40%)的简单 CSS 网格。第一个充满了图片。 当图片有足够的高度时,图片可以很好地包含在网格内。

问题是当它没有足够的高度时,图片高度溢出。
我希望它留在网格内并填充它的任何窗口大小。

代码如下:

.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/

【问题讨论】:

  • 移除 .container 高度并检查!
  • 好的,但我希望我的容器具有 100vh 的固定宽度
  • 图片上需要 min-height:0

标签: html css css-grid


【解决方案1】:

将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

【讨论】:

  • 它将在大屏幕上创建空白
【解决方案2】:

您可以将容器上的高度设置为 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>

【讨论】:

  • overflow: hidden 是诀窍
  • @William 真棒!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
相关资源
最近更新 更多