【问题标题】:Understanding flex-grow了解 flex-grow
【发布时间】:2018-03-09 00:26:24
【问题描述】:

我有 3 个 div,如果我给前两个 div 提供flex: 0.5,如果我给了flex-wrap: wrap,最后一个 div 应该移到下一行。如有错误请指正。

以下是我的html/css:

.parent {
  display: flex;
  height: 100px;
  background-color: red;
  flex-wrap: wrap;
}
.child-1 {
  background-color: green;
  flex: 0.5;
}
.child-2 {
  background-color: yellow;
  flex: 0.5;
}
.child-3 {
  background-color: pink;
}
<div class="parent">
  <div class="child-1">LOREN IPSUM LOREN IPSUM</div>
  <div class="child-2">LOREN IPSUMLOREN IPSUMLOREN IPSUM</div>
  <div class="child-3">LOREN IPSUMLOREN IPSUM</div>
</div>

请检查JSFiddle

提前致谢。

【问题讨论】:

  • 看来你要flex: 50%,和flex: 0.5不一样。

标签: html css flexbox flex-grow


【解决方案1】:

flex-grow 属性旨在将容器中的可用空间分配给弹性项目。

不是用于直接或精确调整弹性项目的大小。

来自spec

flex-grow ... 确定弹性项目将相对增长多少 当正释放时到 flex 容器中的其余 flex 项目 空间分布。

因此,flex-grow 不会强制包裹物品。这是flex-grow: 1000 的示例:demo

要定义弹性项目的长度,请使用widthheightflex-basis


解释flex-grow: 0.5

当您应用flex:0.5 时,您使用的是flex 速记属性来表示:

  • flex-grow: 0.5
  • flex-shrink: 1
  • flex-basis: 0

flex-grow 组件代表一个比例。在这种情况下,它告诉弹性项目消耗容器中相对于其兄弟姐妹的flex-grow 因子的一半可用空间。

因此,例如,如果容器是 width: 600px 并且三个 div 的总宽度为 450px,这将留下 150px 的可用空间 (demo)。

如果每个项目都有flex-grow: 1,那么每个项目将消耗 50px 的额外空间,每个项目将计算为 width: 200px (demo)。

但在您的代码中,两个项目有flex-grow: 0.5,最后一个项目有flex-grow: 0,所以它是这样分解的:

  • div#1 将获得 75 像素(可用空间的一半)
  • div#2 将获得 75 像素(可用空间的一半)
  • div#3 将得到 0(因为它的 flex-grow 为 0)

这些是现在的计算值:

  • div#1 = width: 225px
  • div#2 = width: 225px
  • div#3 = width: 150px

demo

.parent {
  display: flex;
  flex-wrap: wrap;
  height: 100px;
  background-color: red;
  width: 600px;
}

.parent > div {
  flex-basis: 150px;
}

.child-1 {
  flex: 0.5;
  background-color: green;
}

.child-2 {
  flex: 0.5;
  background-color: yellow;
}

.child-3 {
  background-color: pink;
}
<div class="parent">
  <div class="child-1">LOREN IPSUM LOREN IPSUM</div>
  <div class="child-2">LOREN IPSUMLOREN IPSUMLOREN IPSUM</div>
  <div class="child-3"> LOREN IPSUMLOREN IPSUM</div>
</div>

注意:事情的真相是,因为 div #1 和 #2 具有相同的 flex-grow 因子,而 div #3 的因子为 0,所以该值无关紧要。您可以使用任何数字来代替 0.5。只要两个 div 中的相同,项目将计算为 225px,因为比例将相同。

更多信息:

【讨论】:

    猜你喜欢
    • 2020-01-04
    • 2014-02-24
    • 2016-05-25
    • 2017-06-27
    • 2021-11-15
    • 1970-01-01
    • 2022-11-26
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多