HTML/CSS 按钮和 A link 垂直对齐

HTML/CSS Button and A link vertical alignment

我想将 <button><a> 元素垂直居中。我为每个使用 CSS 内联块 属性。奇怪的是,我的<a>link被下移了

button,
.btn {
  display: inline-block;
  padding: 0;
  margin: 0;
  margin-left: 10px;
  color: #ffffff;
  background-color: #00ade0;
  border: 2px solid #fff;
  height: 4rem;
  width: 4rem;
  font-size: 1.5rem;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  line-height: 0;
  text-align: center;
  text-decoration: none;
}
<button>
  1
</button>
<button>
  2
</button>
<a href="#" class="btn">
  3
</a>

我知道如果我改变行高,它可以解决问题,但我不知道为什么 line-height:0,我无法实现我想要的。

您可以为此使用 flexbox。将 buttonsa 标签包装在容器中并使用 flex 属性。我还添加了 box-sizing: border-box 以确保元素之间的一致性。如果您有任何问题,请告诉我。

.container {
  display: flex;
  align-items: center;
}

button,
.btn {
  padding: 0;
  margin: 0;
  margin-left: 10px;
  color: #ffffff;
  background-color: #00ade0;
  border: 2px solid #fff;
  height: 4rem;
  width: 4rem;
  font-size: 1.5rem;
  -webkit-border-radius: 50%;
  -moz-border-radius: 50%;
  border-radius: 50%;
  text-decoration: none;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: sans-serif;
  box-sizing: border-box;
}
<div class="container">
  <button>
    1
  </button>
  <button>
    2
  </button>
  <a href="#" class="btn">
  3
</a>
</div>

问题似乎与您指定 widthheight 有关,尽管还有其他多余的声明(例如 border-radius 的特定于浏览器的声明)。如果我们用 padding 替换 widthheight ……你会得到更一致的结果:`

button, .btn {
    display: inline-block;
    padding: 1rem 1.5rem;
    margin: 0;
    margin-left: 10px;
    box-sizing: border-box;

    color: #ffffff;
    background-color: #00ade0;

    border: 2px solid #fff;
    border-radius: 999px;
    
    text-align: center;
    text-decoration: none;
    font: 1.5rem Helvetica, sans-serif;
}
<button>
  1
</button>
<button>
  2
</button>
<a href="#" class="btn">
  3
</a>

我将您的 border-radius 更改为高得离谱的像素数,因为(根据我的经验)在尝试实现真实圆圈时,这似乎比百分比提供了更多的一致性。为了保持一致性,我还添加了 box-sizing,并为所有项目指定了一种字体,因为 <button> 似乎具有浏览器定义的字体,可能与默认字体不同(将用于 <a>)

我只是想知道为什么在已经有 <button> 元素的情况下使用 <a> 元素。它在您的 HTML/CSS 上稍作修改即可正确显示。 这是您的 HTML 代码:

<button>1</button>
<button>2</button>
<button>3</button>

还有你的 CSS :

 button
 {
   display: inline-block;
   padding: 0;
   margin: 0;
   margin-left: 10px;
   color: #ffffff;
   background-color: #00ade0;
   border: 2px solid #fff;
   height: 4rem;
   width: 4rem;
   font-size: 1.5rem;
   -webkit-border-radius: 50%;
   -moz-border-radius: 50%;
   border-radius: 50%;
  }

通过放置 <a> 元素,我假设您想在按钮上添加点击操作。如果是这种情况,您可以像这样 Javascript 来完成它:

var buttons = document.body.querySelectorAll('button');
  for(var i = 0, c = buttons.length; i < c; i++) {
    buttons[i].addEventListener('click', function() {
      //Redirect user with your links here
    });
  }