Flexbox无法在< button>元素 [英] Flexbox not working on <button> element in some browsers
问题描述
我试图用flexbox的 justify-content:center $ c $来将
< button>
c>。但Safari不会使它们居中。我可以应用相同的样式任何其他标签,它的工作原理(参见< p>
-tag)。只有按钮左对齐。
尝试Firefox或Chrome,您可以看到差异。
有没有任何用户代理风格我不得不覆盖?或此问题的任何其他解决方案?
div {display:flex; flex-direction:column; width:100%;} button,p {display:flex; flex-direction:row; justify-content:center;}
< div& < button> < span>测试< / span> < span>测试< / span> < / button> < p> < span>测试< / span> < span>测试< / span> < / p>< / div>
:
http://jsfiddle.net/z3sfwtn2/2/
根据浏览器的不同,某些HTML元素不会接受 display
更改。其中三个元素是:
-
< button>
-
< fieldset>
-
< legend>
这个想法是在为HTML元素设计样式时保持常识。例如,该规则阻止作者将字段集转换为表。
但是,在这种情况下有一个简单的解决方法:
解决方案:将
按钮
的内容包含在,并使
span
flex容器。
已调整的HTML (包含按钮
内容 span
)
< div>
< button>
< span><! - 使用div也可以,但是无效HTML - >
< span>测试< / span>
< span>测试< / span>
< / span>
< / button>
< p>
< span> Test< / span>
< span>测试< / span>
< / p>
< / div>
调整的CSS (目标 span
)
按钮> span,p {
display:flex;
flex-direction:row;
justify-content:center;
}
注意:虽然不能使用flex容器,但按钮
参考文献:
I'm trying to center inner elements of a <button>
-tag with flexbox's justify-content: center
. But Safari does not center them. I can apply the same style to any other tags and it works as intended (see the <p>
-tag). Only the button is left-aligned.
Try Firefox or Chrome and you can see the difference.
Is there any user agent style I have to overwrite? Or any other solution to this problem?
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>
And a jsfiddle: http://jsfiddle.net/z3sfwtn2/2/
The problem is that the <button>
element cannot be a flex container in some browsers.
Depending on the browser, certain HTML elements will not accept display
changes. Three of these elements are:
<button>
<fieldset>
<legend>
The idea is to maintain a level of common sense when styling HTML elements. For instance, the rule prevents authors from turning a fieldset into a table.
However, there is an easy workaround in this case:
Solution: Wrap the content of the
button
in aspan
, and make thespan
the flex container.
Adjusted HTML (wrapped button
content in a 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>
Adjusted CSS (targeted span
)
button > span, p {
display: flex;
flex-direction: row;
justify-content: center;
}
NOTE: Although they cannot be flex containers, button
elements can be flex items.
References:
- Bug 984869 - display: flex doesn't work for button elements
- Bug 1176786 - Flexbox on a blockifies the contents but doesn't establish a flex formatting context
这篇关于Flexbox无法在< button>元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!