CSS替代中心

Ran*_*lue 6 css center

人们对center标签不屑一顾,但对我而言,它总能以我想要的方式运作.不过,center已弃用,所以我会努力.

现在我看到很多人建议使用神秘的CSS,margin: 0 auto;但我甚至无法使用它(请参阅此处的小提琴).其他人会修改positiondisplay,但这总是打破其他东西.

如何span使用css 居中,使其行为与center标签完全相同?

<div class="container">
  <span class='btn btn-primary'>Click me!</span>
</div>
Run Code Online (Sandbox Code Playgroud)

cim*_*non 8

Span是一个内联元素,margin: 0 auto而居中仅适用于宽度小于100%的非内联元素.

一种选择是在容器上设置对齐,尽管这可能不是您想要的情况:

div.container { text-align: center }
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

使用display: table消除了对特定宽度进行硬编码的需要.它会根据其内容缩小或增长.

http://jsfiddle.net/MgcDU/1271/

  • 这就是我讨厌CSS的那种东西.`display:table`,WTF? (5认同)