【问题标题】:centering a button using css [duplicate]使用css居中按钮[重复]
【发布时间】:2016-08-26 08:32:31
【问题描述】:

我的按钮无法居中,不知道为什么它不起作用。

这里是 html 和 CSS。

.button {
  margin:auto;
  display: inline-block;
  height: 100px;
  width: 300px;
  background: #00007f;
  border: 2px solid rgba(192, 192, 192, 0.59);
  border-radius: 50px;
  padding: 15px 20px;
  color: rgba(172, 172, 172, 0.55);
  font: bold 3em/100px "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
  box-shadow:0 4px 0 #ACACAC;
}

a.button {
  text-decoration: none;
}
<a href="blabla.html" class="button"  style= "text-align: center"> Start Game</a>

【问题讨论】:

  • 你为什么不google这个?这是 CSS 中最常见的问题,非常基本的问题。

标签: html css


【解决方案1】:

居中内联元素和块元素的方式不同。

在您的情况下,您尝试使用用于居中块元素的margin: auto,但您将按钮设置为inline-block。只需将按钮更改为display: block 即可。

.button {
  margin:auto;
  display: block;
  height: 100px;
  width: 300px;
  background: #00007f;
  border: 2px solid rgba(192, 192, 192, 0.59);
  border-radius: 50px;
  padding: 15px 20px;
  color: rgba(172, 172, 172, 0.55);
  font: bold 3em/100px "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
  box-shadow:0 4px 0 #ACACAC;
}

a.button {
  text-decoration: none;
}
<a href="blabla.html" class="button"  style= "text-align: center"> Start Game</a>

【讨论】:

  • 使用block 是个坏主意。它迫使您使用固定宽度,这只会使设计复杂化。按钮上下文应规定宽度。
  • @RokoC.Buljan 该元素已经有固定大小。为什么要打呢?如果这是设计,那么将锚与该属性保持一致并没有错。设计可能有各种我不知道的约束(例如,由于设计的内部一致性,所有按钮都必须具有固定大小)。
【解决方案2】:

在包含按钮集的父级

text-align: center;

喜欢:

.button {
  white-space: nowrap;
  display: inline-block;
  background: #00007f;
  border: 2px solid rgba(192, 192, 192, 0.59);
  border-radius: 50px;
  padding: 15px 40px;
  color: rgba(172, 172, 172, 0.55);
  font: bold 3em/100px "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
  box-shadow:0 4px 0 #ACACAC;
}

a.button {
  text-decoration: none;
}

/* HELPER CLASSES:*/
.text-center{text-align:center;}
<p class="text-center">
  <a href="blabla.html" class="button"> Start Game</a>
</p>

并从您的按钮中删除宽度和高度 - 会让事情变得更容易。

【讨论】:

    猜你喜欢
    • 2018-12-06
    • 2017-12-05
    • 2012-02-05
    • 2021-05-11
    • 2013-09-13
    • 2013-10-30
    • 2013-06-06
    • 1970-01-01
    • 2014-08-02
    相关资源
    最近更新 更多