我有一个包含两个元素的 flexbox 布局。其中之一使用 padding-bottom :
#flexBox {
border: 1px solid red;
width: 50%;
margin: 0 auto;
padding: 1em;
display: flex;
flex-direction: column;
}
#text {
border: 1px solid green;
padding: .5em;
}
#padding {
margin: 1em 0;
border: 1px solid blue;
padding-bottom: 56.25%; /* intrinsic aspect ratio */
height: 0;
}
<div id='flexBox'>
<div id='padding'></div>
<div id='text'>Some text</div>
</div>
蓝色元素maintains its aspect ratio according to its width调整页面大小时。 这适用于 Chrome 和 IE,看起来像:
但是,在 Firefox 和 Edge 中,我得到以下信息(它忽略了蓝色框上的填充,这是保持纵横比的原因):
我对 flexbox 太陌生了,无法真正理解这是否应该起作用。 flexbox 的全部意义在于调整大小,但我不确定为什么它会忽略内在填充,并将绝对大小放在蓝色元素上。
我想最终我什至不确定 Firefox 或 Chrome 是否在做正确的事情!任何 Firefox flexbox 专家都可以提供帮助吗?
最佳答案
2020 年 9 月更新
Firefox 和 edge 已经实现了规范中的行为,flex 元素的 margin + padding 都是根据包含 block 的 width 计算的。
就像 block 元素一样。
2018 年 2 月更新
Firefox 和 edge 已同意更改它们在 flex(和网格)元素的顶部、底部边距和填充上的行为:
[...] e.g. left/right/top/bottom percentages all resolve against their containing block’s width in horizontal writing modes. [source]
这还没有实现(在 FF 58.0.2 上测试过)。
2016 年 4 月更新
规范有 been updated到:
Percentage margins and paddings on flex items can be resolved against either:
- their own axis (left/right percentages resolve against width, top/bottom resolve against height), or,
- the inline axis (left/right/top/bottom percentages all resolve against width)
来源:CSS Flexible Box Layout Module Level 1
这意味着 chrome IE FF 和 Edge(即使它们没有相同的行为)遵循规范建议。
规范还说:
Authors should avoid using percentages in paddings or margins on flex items entirely, as they will get different behavior in different browsers. [source]
解决方法
您可以将 flex 容器的第一个子元素包裹在另一个元素中,并将 padding-bottom
放在第二个元素上:
#flexBox {
border: 1px solid red;
width: 50%;
margin: 0 auto;
padding: 1em;
display: flex;
flex-direction: column;
}
#text {
border: 1px solid green;
padding: .5em;
}
#padding {
margin: 1em 0;
border: 1px solid blue;
}
#padding > div {
padding-bottom: 56.25%; /* intrinsic aspect ratio */
}
<div id='flexBox'>
<div id='padding'><div></div></div>
<div id='text'>Some text</div>
</div>
我在现代浏览器(IE、chrome、FF 和 Edge)中对此进行了测试,它们都具有相同的行为。由于第二个 child 的配置“与往常一样”,我想较旧的浏览器(也是 support flexbox layout module )将呈现相同的布局。
上一个答案
根据specs , Firefox 有正确的行为
解释
与根据容器宽度计算其边距/填充百分比的 block 元素不同,在 flex 元素上:
Percentage margins and paddings on flex items are always resolved against their respective dimensions; unlike blocks, they do not always resolve against the inline dimension of their containing block.
这意味着 padding-bottom/top 和 margin-bottom/top 是根据容器的高度计算的,而不是非 flexbox 布局中的宽度。
由于您没有在父 flex 元素上指定任何高度,因此子项的底部填充应该为 0px。
这是一个fiddle在父级上具有固定高度,表明填充底部是根据 display:flex;
容器的高度计算的。
关于css - flexbox 布局中的填充底部/顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23717953/