html - 为什么使用 Flex Wrap 会破坏包含大图像的元素的高度?

标签 html css flexbox

我使用启用了 Flexbox 的容器和 2 个子 div 设置了一个简单的页面。

大小是使用容器的 View 宽度和 View 高度设置的。

使用 css flex 简写将子 div 设置为 600px 和 400px 宽度。

已将大图像添加到子图像中,并将其大小调整为 100%。

在容器上启用 flex-wrap:wrap 之前,这一切都可以正常工作。

然后 children 的高度突然变大了。

有办法解决这个问题吗?

下面是我的代码。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.flex-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-wrap: wrap;
}

.flex-item1 {
  flex: 1 1 600px;
  padding: 20px;
  background-color: coral;
}

.flex-item2 {
  flex: 1 1 400px;
  padding: 20px;
  background-color: cornflowerblue;
}

.image {
  height: 100%;
  width: 100%;
  object-fit: contain;
}
<div class="flex-container">
  <div class="flex-item1">
    <img src="https://picsum.photos/1000/2000" class="image" alt="image" />
  </div>
  <div class="flex-item2">
    <h1>Header 1</h1>
  </div>

最佳答案

只需将其添加到您的代码中即可:

.flex-item1 {
   height: 100%;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.flex-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-wrap: wrap;
}

.flex-item1 {
  flex: 1 1 600px;
  padding: 20px;
  background-color: coral;
  height: 100%; /* new */
}

.flex-item2 {
  flex: 1 1 400px;
  padding: 20px;
  background-color: cornflowerblue;
}

.image {
  height: 100%;
  width: 100%;
  object-fit: contain;
}
<div class="flex-container">
  <div class="flex-item1">
    <img src="https://picsum.photos/1000/2000" class="image" alt="image" />
  </div>
  <div class="flex-item2">
    <h1>Header 1</h1>
  </div>


对于单行 Flex 容器 (flex-wrap: nowrap),容器上的 height: 100%height: 100% 识别 在图像上(向下 2 级)。

对于多行 Flex 容器 (flex-wrap:wrap),容器上的 height: 100% 不会被图像继承。百分比高度链断裂。因此,您需要将 height: 100% 添加到中间链接(Flex 元素),以便布局在两种情况下都能工作。

不太清楚为什么会发生这种情况。得研究一下。

关于html - 为什么使用 Flex Wrap 会破坏包含大图像的元素的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66789876/

相关文章:

java - 网页中的导航/浏览按钮

css - 如何禁用相对于某个父标签的CSS样式?

javascript - 在 Bootstrap 列中居中一个 div

html - 具有静态和可滚动元素的 FlexBox

html - 如何使用 flexbox css 设置顶部底部和右侧内容

javascript - 使用 javascript/Jquery 进行 Ajax

html - 选择与由空白和 css 引起的光标位置不匹配

html - 与 CSS 表格相同高度的列 - 段落标记打破平等

html - 在 flexbox 中将图像缩放到最大尺寸

html - 页脚作为内容居中的 float div - 缩小时保持居中