我最近一直在研究 display:flex
,因为我发现它越来越流行。在快速测试中,使用 flex 和非 flex CSS 方法,我意识到,在使用 flex 时,我的宽度和边距总是受到尊重。考虑到我很可能无论如何都需要在元素之间留出间距,这是一种好方法吗?此外,跨度之间的边距从何而来?这就是我的意思:
HTML
<div class="container">
<div class="box">
<span class="inner-box">This gives me a 30px X 60px</span>
<span class="inner-box">This gives me a 30px X 60px</span>
<span class="inner-box">This gives me a 30px X 60px</span>
</div>
<div class="box2">
<span class="inner-box">This gives me a width larger than the specified 30px</span>
<span class="inner-box">This gives me a width larger than the specified 30px</span>
<span class="inner-box">This gives me a width larger than the specified 30px</span>
</div>
</div>
CSS
.box{
background: orange;
display:flex;
flex-direction:row-reverse;
padding:0 10px;
}
.box2{
background: green;
text-align:right;
padding:0 10px;
}
.inner-box{
width:30px;
background:#fff;
margin:0 0px;
}
最佳答案
您正在使用 <span>
元素。默认情况下它们是内联的。 width
对于内联元素会自动忽略。
在第一个div
节 ( .box
),然而, span
的内联 display
值被父级的 display: flex
覆盖, 它建立了一个 flex formatting context .因此,所有 child 都成为 flex 元素,尊重width
和 height
.
A flex item establishes a new formatting context for its contents. The type of this formatting context is determined by its
display
value, as usual. However, flex items themselves are flex-level boxes, not block-level boxes: they participate in their container’s flex formatting context, not in a block formatting context.
在第二个div
节 ( .box2
), span
元素保留 display: inline
, 因为它们没有从 block-formatting context 中删除, 和任何 width
和 height
分配被忽略。
尝试 display: inline-block
: http://codepen.io/anon/pen/yeggOy
引用资料:
关于html - 为什么宽度在 flexbox 中处理不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34567500/