Flex / Grid 布局不适用于按钮或字段集元素

新手上路,请多包涵

我正在尝试将 <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 许可协议

阅读 350
2 个回答

问题

In some browsers the <button> element doesn’t accept changes to its display value, beyond switching between block and inline-block .这意味着 <button> 元素不能是弹性或网格容器,也不能是 <table>

除了 <button> 元素之外,您可能会发现此约束也适用于 <fieldset><legend> 元素。

有关详细信息,请参阅下面的错误报告。

注意:虽然它们不能是弹性容器, <button> 元素可以是弹性项目。


解决方案

这个问题有一个简单易行的跨浏览器解决方法:

button span ,并使 span 成为 flex 容器。

调整后的 HTML(包装 button 中的内容 span

 <div>
    <button>
        <span><!-- using a div also works but is not valid HTML -->
            <span>Test</span>
            <span>Test</span>
        </span>
    </button>
    <p>
        <span>Test</span>
        <span>Test</span>
    </p>
</div>

调整后的 CSS(目标 span

 button > span, p {
    display: flex;
    flex-direction: row;
    justify-content: center;
}

修改后的演示


参考资料/错误报告

<button> 上的 Flexbox 块化内容但不建立 flex 格式化上下文

用户 (Oriol Brufau): <button> 的孩子被块化了,正如 flexbox 规范所规定的那样。但是, <button> 似乎建立了块格式化上下文而不是弹性上下文。

用户 (Daniel Holbert): 这实际上是 HTML 规范所要求的。几个 HTML 容器元素是“特殊的”并且有效地忽略了它们在 Gecko 中的 CSS display 值 [除了它是内联级还是块级]。 <button> 是其中之一。 <fieldset> & <legend> 也是。

添加对 display:flex/grid 和 columnset layout inside <button> 元素的支持

用户(丹尼尔霍尔伯特):

<button> 不能(通过浏览器)在纯 CSS 中实现,因此从 CSS 的角度来看,它们有点像黑盒子。这意味着它们不一定会像 <div> 那样做出反应。

这不是 flexbox 特有的——例如,如果您将 overflow:scroll 放在按钮上,我们不会呈现滚动条,如果您将 display:table 我们不会将其呈现为表格在上面。

更进一步,这不是特定于 <button> 。考虑 <fieldset><table> 也有特殊的渲染行为。

And old-timey HTML elements like <button> and <table> and <fieldset> simply do not support custom display values, other than for the purposes of回答“这个元素是块级还是内联级”的非常高级的问题,以便在元素周围流动其他内容。

另见:

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是我最简单的技巧。

 button::before,
button::after {
    content: '';
    flex: 1 0 auto;
}

原文由 Igari Takeharu 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏