gpt4 book ai didi

html - 了解 flex 增长

转载 作者:太空狗 更新时间:2023-10-29 13:44:22 26 4
gpt4 key购买 nike

我有 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-grow 属性旨在将容器中的可用空间分配给 flex 元素。

不是用于直接或精确调整 flex 元素的大小。

来自 spec :

flex-grow ... determines how much the flex item will grow relative to the rest of the flex items in the flex container when positive free space is distributed.

因此,flex-grow 不会强制元素换行。这是您使用 flex-grow: 1000: demo

的示例

要定义 flex 元素的长度,请使用 widthheightflex-basis


解释 flex-grow: 0.5

当您应用 flex:0.5 时,您使用的是 flex 简写属性:

  • flex 增长:0.5
  • flex-shrink: 1
  • flex 基础:0

flex-grow 组件表示一个比例。在这种情况下,它告诉 flex 元素消耗 容器中相对于其 sibling 的 flex-grow 因素的一半可用空间

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

如果每个元素都有 flex-grow: 1,那么每个元素将占用 50px 的额外空间,并且每个元素将计算为 width: 200px ( demo ) .

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

  • div#1 will get 75px (half of the available space)
  • div#2 will get 75px (half of the available space)
  • div#3 will get 0 (because its flex-grow is 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 相同,元素就会计算为 225 像素,因为比例相同。

更多信息:

关于html - 了解 flex 增长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37617872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com