【问题标题】:Centering button vertically and horizontally垂直和水平居中按钮
【发布时间】:2016-08-15 00:08:07
【问题描述】:

我有一个很大的“立即购买”按钮,在我的网页上设置为 100 宽。文本以 X 轴(水平)为中心,但不在 y 轴(垂直)中心。这是我的课:

.col-boosting .btn-pay-rank {
height: 65px;
font-weight: bold;
background: #e06b38;
border: none;
box-shadow: 0 7px 0 0 #c7511f;
text-align: center; 
line-height: 65px; }

更多信息,这里是按钮的屏幕截图。 https://gyazo.com/2d0b5fc4be72ba87c9cf73cd922d8ebe

谢谢。

【问题讨论】:

  • 发布更多代码 - 问题可能不在本节中。链接 jsfiddle 是向我们展示这一点的最佳方式:jsfiddle.net
  • 如果浏览器支持适合您,请考虑使用 flexbox。

标签: html css button center


【解决方案1】:

将按钮放在父 div 中并使用这个 css:

body {
  background: #f06d06;
  font-size: 80%;
  padding: 20px;
}
.parent {
  position: relative;
  background: white;
  height: 200px;
  width: 60%;
  margin: 0 auto;
  padding: 20px;
  resize: both;
  overflow: auto;
}
.parent div {
  background: black;
  color: white;
  width: 200px;
  height: 100px;
  margin: -70px 0 0 -120px;
  position: absolute;
  top: 50%;
  left: 50%;
  padding: 20px;
}
<div class="parent">
  <div class="child">
    I'm a block-level element a fixed height and width, centered vertically within my parent.
  </div>
</div>

来自CSS Tricks的替代解决方案:

body {
  background: #f06d06;
  font-size: 80%;
  padding: 20px;
}
main {
  background: white;
  height: 200px;
  width: 60%;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  resize: both;
  overflow: auto;
}
main div {
  background: black;
  color: white;
  width: 50%;
  padding: 20px;
  resize: both;
  overflow: auto;
}
<main>

  <div>
    I'm a block-level-ish element of an unknown width and height, centered vertically within my parent.
  </div>

</main>

【讨论】:

    【解决方案2】:

    将“立即购买”放入

    元素:

    <p>Buy Now</p>
    

    然后对齐:

    p {margin:0 auto;vertical-align:middle;}
    

    【讨论】: