人们不喜欢 center
标签,但对我来说,它总是按照我想要的方式工作。尽管如此,center
已被弃用,所以我会努力。
现在我看到很多人建议使用神秘的 CSS margin: 0 auto;
但我什至不能让它工作(参见 fiddle here )。其他人会去修改 position
或 display
,但这总是会破坏其他东西。
如何使用 css 将 span
居中,使其表现得与 center
标签完全一样?
<div class="container">
<span class='btn btn-primary'>Click me!</span>
</div>
最佳答案
Span
是一个内联元素,用于居中的 margin: 0 auto
仅适用于宽度小于 100% 的非内联元素。
一个选项是在容器上设置对齐方式,虽然这可能不是您想要的这种情况:
div.container { text-align: center }
http://jsfiddle.net/MgcDU/1270/
另一种选择是更改span
的显示属性:
/* needs some extra specificity here to avoid the display being overwritten */
span.btn.btn-primary {
display: table;
margin: 0 auto;
}
使用 display: table
消除了对特定宽度进行硬编码的需要。它会根据其内容适当缩小或扩大。
关于center - CSS替代中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14286597/