【问题标题】:webkit Center equivalent for IE and edgeIE 和边缘的 webkit 中心等效项
【发布时间】:2018-03-25 16:34:50
【问题描述】:

在 IE 上使用 display: block 将按钮居中是否正确,或者我应该寻找一种将 WebKit-center 用于其他浏览器的方法?

@media screen and (max-width: 767px) {
    .flex {
        display:inline-block;
    }
    .flex_height {
        display:inline-block;
    }
    .grid_8 {
        background-repeat:no-repeat;
        width:98%;
        margin-left:1%;
        margin-right:1%;
        text-align:-webkit-center;
        text-align:-moz-center;
        margin-left:auto;
        margin-right:auto;
    }
}
<div class="grid_8">
    <button type="button" class="button_home mobile_on">
    *php code to generate text for a button here*
    </button>
</div>

【问题讨论】:

  • 为什么不text-align: center;
  • 试过了,按钮不动
  • 你的css与html无关
  • @TylerH 我怎样才能让它变得更好?对我应该包含的内容有点困惑

标签: css button text-align


【解决方案1】:

inline-block 将换行到其内容的宽度,因此在inline-block居中按钮毫无意义。

见:

.inline-block {
  display: inline-block;
  background-color: red;
}
<div class="inline-block">
  <button>Button Label</button>
</div>
<p><em>As you can see, the button is already centered inside the red inline-block.</em></p>

相反,您可以使用带有text-align: center 的常规块(非内联)元素来使按钮居中。

div {
  background-color: red;
  text-align: center;
}
<div>
  <button>Button Label</button>
</div>

或者,如果你真的需要这个 inline-block 元素,那么你必须将它全部包装在一个外包装中:

.wrapper {
  text-align: center;
}

.inline-block {
  display: inline-block;
  background-color: red;
}
<div class="wrapper">
  <div class="inline-block">
    <button>Button Label</button>
  </div>
</div>

除此之外,您还可以使用一些 hacks 作为相对定位、负边距或变换。但是,我会尽量保持简单。

.inline-block {
  display: inline-block;
  position: relative;
  left: 50%;
}

#blue {
  background-color: blue;
  margin-left: -41px; /* Magic number. Not recommended! */
}

#red {
  background-color: red;
  transform: translateX(-50%); /* Much better, but still... */
}
<div>
  <div id="blue" class="inline-block">
    <button>Button Label</button>
  </div>
</div>

<div>
  <div id="red" class="inline-block">
    <button>Button Label</button>
  </div>
</div>

【讨论】:

  • 您好,downvoter,您能否为我添加一些建议以改进我的答案?谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 2011-12-04
  • 2012-10-29
  • 2013-11-21
相关资源
最近更新 更多