CSS 将两行按钮水平居中的代码

CSS code to horizontally center a 2-line button

这里是新手。我一直在尝试,但我似乎无法弄清楚这一点。我有一个漂亮的 2 行按钮,效果很好。我想让它在页面上水平居中,但我只能弄清楚如何让它向左或向右移动。

HTML:
<a href="#" target="_blank" class="button">abcd efgh ijk lmn opqrstu<br>(abcd efrghijk + lmno pqurstuvwk)</a>

CSS:
.button {
  width: 250px;
  float: left;
  text-align: center;
  border-top: 1px solid #96d1f8;
  background: #65a9d7;
  background: -webkit-gradient(linear, left top, left bottom, from(#3e779d), to(#65a9d7));
  background: -webkit-linear-gradient(top, #3e779d, #65a9d7);
  background: -moz-linear-gradient(top, #3e779d, #65a9d7);
  background: -ms-linear-gradient(top, #3e779d, #65a9d7);
  background: -o-linear-gradient(top, #3e779d, #65a9d7);
  padding: 9.5px 19px;
  -webkit-border-radius: 13px;
  -moz-border-radius: 13px;
  border-radius: 13px;
  -webkit-box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
  -moz-box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
  box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
  text-shadow: rgba(0, 0, 0, .4) 0 1px 0;
  color: white;
  font-size: 16px;
  font-family: Georgia, serif;
  text-decoration: none;
  vertical-align: middle;
}

.button:hover {
  border-top-color: #28597a;
  background: #28597a;
  color: #ccc;
}

.button:active {
  border-top-color: #1b435e;
  background: #1b435e;
}

使用行高:

    a { line-height: 50px; }

这仅在文本占一行时有效。如果你必须处理多行,你可以使用 display: table-cell:

    a { display: table-cell; vertical-align: middle; }

或检查此 link .

在您的 CSS 中添加以下内容:

display: block;
margin: 0 auto;

并删除:

float: left;

JSFiddle:http://jsfiddle.net/om8vgnb7/

您的 float: left; 是不必要的,并且不允许您将按钮置于任何内容的中心。

float: left; 替换为 display: inline-block;

然后你可以这样做:

<div style="text-align: center;">
    <a href="#" class="button">My Button</a>
</div>

Flexbox 解决方案: 将按钮包裹在容器中并使用 flexbox。从按钮中移除浮动。

.container {
  display: flex;
  justify-content: center;
}
.button {
  width: 250px;
  text-align: center;
  border-top: 1px solid #96d1f8;
  background: #65a9d7;
  background: -webkit-gradient(linear, left top, left bottom, from(#3e779d), to(#65a9d7));
  background: -webkit-linear-gradient(top, #3e779d, #65a9d7);
  background: -moz-linear-gradient(top, #3e779d, #65a9d7);
  background: -ms-linear-gradient(top, #3e779d, #65a9d7);
  background: -o-linear-gradient(top, #3e779d, #65a9d7);
  padding: 9.5px 19px;
  -webkit-border-radius: 13px;
  -moz-border-radius: 13px;
  border-radius: 13px;
  -webkit-box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
  -moz-box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
  box-shadow: rgba(0, 0, 0, 1) 0 1px 0;
  text-shadow: rgba(0, 0, 0, .4) 0 1px 0;
  color: white;
  font-size: 16px;
  font-family: Georgia, serif;
  text-decoration: none;
  vertical-align: middle;
}
.button:hover {
  border-top-color: #28597a;
  background: #28597a;
  color: #ccc;
}
.button:active {
  border-top-color: #1b435e;
  background: #1b435e;
}
<div class="container">
  <a href="#" target="_blank" class="button">abcd efgh ijk lmn opqrstu<br>(abcd efrghijk + lmno pqurstuvwk)</a>
</div>