【问题标题】:Flex box to assign largest child width to other child width将最大子宽度分配给其他子宽度的 Flex 框
【发布时间】:2017-04-12 18:55:57
【问题描述】:

我有一组宽度应该相似的孩子。要成为具有最大宽度的简单子级,应将其分配给其他子级。我尝试使用 flexbox 但无法获得它。是否可以在 flex box 中实现,或者我应该选择JS 解决方案。请参考我尝试过的示例。请不要为此发布任何 javascript 答案。

.flex{
  display:flex;
  flex-direction:column;
  align-items:baseline
}
.flex > div{
  background:#aaa
}
<div class="flex">
  <div>
      Text to check
  </div>
    <div>
      Text to check for similar width
  </div>
   <div>
      Text to check for similar width - will it work
  </div>
</div>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    使用display:inline-flex; 并赋予项目100% 的宽度。

    .flex{
      display:inline-flex;
      flex-direction:column;
      align-items:baseline
    }
    .flex > div{
      background:#aaa;
      width: 100%;
    }
    <div class="flex">
      <div>
          Text to check
      </div>
        <div>
          Text to check for similar width
      </div>
       <div>
          Text to check for similar width - will it work
      </div>
    </div>

    已更新,感谢 @vals comment

    或将container 上的align-items: stretch 更改为width: 100% 在项目上。

    .flex{
      display:inline-flex;
      flex-direction:column;
      align-items:stretch;
    }
    .flex > div{
      background:#aaa
    }
    <div class="flex">
      <div>
          Text to check
      </div>
        <div>
          Text to check for similar width
      </div>
       <div>
          Text to check for similar width - will it work
      </div>
    </div>

    【讨论】:

    • 好答案!此外,还可以更改 align-items:stretch;在容器上
    【解决方案2】:

    根本不需要使用 flex 或 floats。

    只需给父容器一个显示声明inline-block。

    父级的宽度将扩大以适应最宽的子级的宽度 - 但仅此而已。

    同时,由于所有子元素都是块级元素,它们的宽度都会扩展以匹配父容器的宽度。

    即。 所有子块级元素都将以与最宽子元素相同的宽度显示。

    示例:

    .inline-block {
    display: inline-block;
    }
    
    .inline-block > div {
    margin: 6px;
    padding: 12px;
    background-color:#aaa
    }
    <div class="inline-block">
    <div>Text to check</div>
    <div>Text to check for similar width</div>
    <div>Text to check for similar width - will it work?</div>
    </div>

    【讨论】:

    • Plus 1 提供出色的浏览器支持 :)
    【解决方案3】:

    .flex {
      width: auto;
      float: left;
    }
    .flex > div {
      background: #aaa;
      width: 100%;
    }
    <div class="flex">
      <div>
          Text to check
      </div>
        <div>
          Text to check for similar width
      </div>
       <div>
          Text to check for similar width - will it work
      </div>
    </div>

    不需要弹性。你可以这样试试。

    【讨论】:

      猜你喜欢
      • 2019-09-12
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 2020-11-09
      相关资源
      最近更新 更多