伸缩项目宽度伸缩方向:列和边距:0自动 [英] Flex item width flex-direction: column and margin: 0 auto
问题描述
为什么将 A 项设置为margin: 0 auto
时,它不占用容器的整个宽度?
Why doesn't flex item A take the full width of the container when it's set to margin: 0 auto
?
jsfiddle
.container {
display: flex;
flex-direction: column;
}
.a {
margin: 0 auto;
border: 1px solid red;
}
.b {
border: 1px solid blue;
}
<div class="container">
<div class="a">A</div>
<div class="b">B</div>
</div>
推荐答案
这就是flexbox布局算法的工作方式.在这种情况下,适用以下条件:
That's how the flexbox layout algorithm works. In this case, the following applies:
弹性项目上的自动边距效果与块流中的自动边距效果非常相似:
Auto margins on flex items have an effect very similar to auto margins in block flow:
-
在计算伸缩度和柔性长度期间,自动边距被视为0.
During calculations of flex bases and flexible lengths, auto margins are treated as 0.
在通过justify-content
和align-self
对齐之前,任何正的自由空间都会分配给该维度中的自动边距.
Prior to alignment via justify-content
and align-self
, any positive free space is distributed to auto margins in that dimension.
在您的情况下,您看到的自由空间平均分布在元素的两侧.这是布局算法的另一点:
In your case, you are seeing the free space distributed equally on both sides of the element. Here is another point taken from the layout algorithm:
分配所有剩余的可用空间.对于每条柔性线: 如果剩余的可用空间为正,并且该行上至少有一个主轴空白为自动,请在这些空白中平均分配可用空间.否则,将所有自动边距设置为零. 沿每个对齐内容对齐主轴内容.
Distribute any remaining free space. For each flex line: If the remaining free space is positive and at least one main-axis margin on this line is auto, distribute the free space equally among these margins. Otherwise, set all auto margins to zero. Align the items along the main-axis per justify-content.
这篇关于伸缩项目宽度伸缩方向:列和边距:0自动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!