我正在尝试将 <button>
标签的内部元素与 flexbox 的 justify-content: center
。但 Safari 不会将它们居中。我可以将相同的样式应用于任何其他标签,并且它按预期工作(请参阅 <p>
标签)。只有按钮是左对齐的。
尝试使用 Firefox 或 Chrome,您会发现不同之处。
是否有任何我必须覆盖的用户代理样式?或者这个问题的任何其他解决方案?
div {
display: flex;
flex-direction: column;
width: 100%;
}
button, p {
display: flex;
flex-direction: row;
justify-content: center;
}
<div>
<button>
<span>Test</span>
<span>Test</span>
</button>
<p>
<span>Test</span>
<span>Test</span>
</p>
</div>
还有一个 jsfiddle:http: //jsfiddle.net/z3sfwtn2/2/
原文由 Ingemar 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题
In some browsers the
<button>
element doesn’t accept changes to itsdisplay
value, beyond switching betweenblock
andinline-block
.这意味着<button>
元素不能是弹性或网格容器,也不能是<table>
。除了
<button>
元素之外,您可能会发现此约束也适用于<fieldset>
和<legend>
元素。有关详细信息,请参阅下面的错误报告。
注意:虽然它们不能是弹性容器,
<button>
元素可以是弹性项目。解决方案
这个问题有一个简单易行的跨浏览器解决方法:
将
button
span
,并使span
成为 flex 容器。调整后的 HTML(包装
button
中的内容span
)调整后的 CSS(目标
span
)修改后的演示
参考资料/错误报告
<button>
上的 Flexbox 块化内容但不建立 flex 格式化上下文添加对 display:flex/grid 和 columnset layout inside
<button>
元素的支持另见: