【问题标题】:How to make a flex item fill empty space under another adjacent flex item (wrapping)如何使弹性项目填充另一个相邻弹性项目下的空白空间(包装)
【发布时间】:2023-03-28 16:43:01
【问题描述】:

我想让一个弹性项目在另一个较短的相邻弹性项目下伸展,这样它就可以填充任何空白空间。

在以下代码笔中,“第一项”(绿色背景)应填充第二项(粉红色背景)下方的空间。

这里是代码笔: https://codepen.io/anon/pen/bKaygK

这里是代码:

html

<div class='wrap'>
  <div class='first-item'>
    <div>some text</div>
    <div>some more text</div>
    <div>some more text again</div>
  </div>
  <div class='second-item'>some box</div>
</div>

css

.wrap {
  display: flex;
  /*flex-wrap: wrap; not working*/
}

.first-item {
  background: lightgreen;
}

.second-item {
  align-self: baseline;
  background: pink; 
}

【问题讨论】:

    标签: css flexbox


    【解决方案1】:

    我认为最好依靠 old 浮动技术来实现这一点:

    .wrap {
      display: inline-block;
    }
    
    .first-item {
      background: lightgreen;
    }
    
    .second-item {
      background: pink; 
      float:right;
    }
    <div class='wrap'>
      
      <div class='second-item'>some box</div>
      <div class='first-item'>
        <div>some text</div>
        <div>some more text</div>
        <div>some more text again</div>
      </div>
    </div>

    【讨论】:

      【解决方案2】:

      我认为如果你添加第三个项目可以做到期望的结果,这实际上是包含第一个和第二个项目的第二个包装。这似乎意味着,如果你将一个 flex 容器放在另一个 flex 容器中,那么即使没有明确定义,内部的 flex 容器也会隐式地成为其包含的 flex 容器的 flex 项。

      .first-wrap {
        display: flex;
        
      /*   flex-wrap: nowrap; */
      }
      
      .second-wrap {
        display: flex;
      }
      
      .first-item {
        background: lightgreen;
        
      }
      
      .second-item {
        align-self: baseline;
        background: pink;
      }
      
      
      .second-wrap {
       background: lightgreen;
       }
      <div class='first-wrap'>
        <div class='second-wrap'>
        <div class='first-item'>
          <div>some text</div>
          <div>some more text</div>
          <div>some more text again</div>
        </div>
        
        <div class='second-item'>some box</div>
        <div>
      </div>

      【讨论】: