【问题标题】:setting the height of an image within a flex-wrap element在 flex-wrap 元素中设置图像的高度
【发布时间】:2018-01-08 08:08:21
【问题描述】:

如果我使用 flex box wrap 创建一个 2x2 的 div 网格,然后在每个 div 中放置一个图像:-

<div id="wrapper">
  <div class="item"><img src="http://via.placeholder.com/100x500"></div>
  <div class="item"><img src="http://via.placeholder.com/100x500"></div>
  <div class="item"><img src="http://via.placeholder.com/100x500"></div>
  <div class="item"><img src="http://via.placeholder.com/100x500"></div>
</div>

#wrapper {
  display: flex;
  flex-wrap: wrap;
  height: 100vh;
  background-color: burlywood;
}
.item {
  flex-grow: 1;
  width: 50%;
  background-colour: bisque;
}

如果图像的本机高度比 flex 项目更深,它会将我的内容推到比我设置包装器的 100vh 更深的位置。

我希望每个图像都填充其弹性项目 div 的高度,在本例中为屏幕高度的 50%,并且图像宽度具有正确的比例。

我尝试将图像高度设置为其容器的 100%,但无法正常工作。 (除非图片原生高度更短,否则它会展开以适应)。

如果我将弹性项目 div 的高度明确设置为 33.333%,它也可以工作,但这对我来说似乎不是正确的解决方案。

【问题讨论】:

  • 我希望避免涉及设置 .item div 高度的解决方案,尽管它在这个简单的示例中有效,但它会给我的其余布局带来更多问题
  • 他们的最大高度而不是高度怎么样?这会打乱布局吗?
  • 我正在设置一些具有固定 px 大小的元素,并通过将一个元素设置为 flex-grow 来填充其余的空白空间,如果我必须给该元素一个大小,甚至我认为是最大值size 不行,我想我需要回到绘图板上。

标签: html css flexbox


【解决方案1】:

您只需设置图片的高度以使其保持正确的比例。将以下类添加到您的 CSS 以应用 50vh 的高度,如果我理解正确,我认为您的问题将得到解决。

.item img {
  height:50vh;
}

之后您可以进行调整以获得所需的内容。

希望这会有所帮助。

【讨论】:

  • 感谢@trevorp 正确格式化我的答案。
【解决方案2】:

另一种解决方案是将.item 的高度设置为50%,并为.item img 设置一个最大高度,如下所示:

#wrapper {
  display: flex;
  flex-wrap: wrap;
  height: 100vh;
  background-color: burlywood;
}
.item {
  flex-grow: 1;
  width: 50%;
  background-color: bisque;
  height: 50%;
}
.item > img {
  max-height: 100%;
}
<div id="wrapper">
  <div class="item"><img src="http://via.placeholder.com/100x500"></div>
  <div class="item"><img src="http://via.placeholder.com/100x500"></div>
  <div class="item"><img src="http://via.placeholder.com/100x500"></div>
  <div class="item"><img src="http://via.placeholder.com/100x500"></div>
</div>

这里是a fiddle,如果您愿意的话。

【讨论】:

  • 这里是another fiddle,它将显示轮廓 - 只是因为这样更容易看到它在哪里工作...... :)
猜你喜欢
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 2017-08-30
相关资源
最近更新 更多