Flexbox无法处理按钮或字段集元素

时间:2016-02-17 17:49:33

标签: html css css3 safari flexbox

我正在尝试使用flexbox的<button>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>

还有一个小提琴: http://jsfiddle.net/z3sfwtn2/2/

3 个答案:

答案 0 :(得分:102)

问题是<button>元素不是设计为flex(或网格)容器。

在撰写本文时,基于Webkit的浏览器(Chrome和Safari)遵循这一设计原则。 Firefox和Edge没有。我没有测试其他浏览器。

因此,在Firefox和Edge中将<button>元素设置为flex(或网格)容器应该没有问题。但不要指望它可以在Chrome或Safari中使用。

此行为目前适用于至少三个元素:

  • <button>
  • <fieldset>
  • <legend>

我是理论化的,但我相信这个想法是在设计HTML元素时保持一定的常识。例如,HTML众神希望阻止作者将按钮变成表格。

但是,至少在这种情况下,有一个简单易用的解决方法

  

button的内容包含在span中,并将span设为灵活容器。

调整后的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;
}

Revised Demo

注意:虽然它们不能是flex容器,但button元素可以是flex项目。

参考文献:

答案 1 :(得分:12)

这是我最简单的黑客攻击。

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

答案 2 :(得分:1)

从Chrome 83开始,button现在可以用作inline-grid/grid/inline-flex/flex,您可以了解有关此新功能here

的更多信息

以下为摘要(适用于使用Chrome 83及更高版本的用户)

button {
  display: inline-flex;
  height: 2rem;
  align-items: flex-end;
  width: 4rem;
  -webkit-appearance: none;
  justify-content: flex-end;
}
<!-- 

The align-items keyword should fail in Chrome 81 or earlier, but work in Chrome 83 or later. To see the error, the button needs styles that make it more of an extrinsic container. In other words, it needs a height or width set. 
 
-->
<button>Hi</button>
<input type="button" value="Hi">