【问题标题】:Why does using flex wrap break the height of an item containing large images?为什么使用 flex wrap 会破坏包含大图像的项目的高度?
【发布时间】:2021-03-24 21:46:43
【问题描述】:

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

使用容器的视图宽度和视图高度设置大小。

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

已将一张大图片添加到子 1 并调整为 100%。

在容器上启用flex-wrap: wrap 之前,这一切正常。

然后孩子们的身高突然变大了。

有没有办法解决这个问题?

下面是我的代码。

* {
  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>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

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

    .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 项),以使布局在这两种情况下都能正常工作。

    不完全确定为什么会发生这种情况。必须研究它。

    【讨论】:

    • 这解决了问题!谢谢你,我想疯了。肯定会研究这个,现在我知道问题是什么了。
    猜你喜欢
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 2018-01-08
    • 1970-01-01
    • 2014-07-21
    • 2015-11-30
    • 2020-11-23
    相关资源
    最近更新 更多