【问题标题】:How do I vertically center an <a> element within a flex div?如何在 flex div 中垂直居中 <a> 元素?
【发布时间】:2017-02-02 01:44:02
【问题描述】:

为什么我可以用 flex 使按钮居中而不是链接?

#quote-btn-div {
  display: flex;
}
#quote-btn,
#twitter-link {
  background-color: #999;
  /* Green */
  border: none;
  width: 300px;
  height: 100px;
  margin: 0 auto;
  color: white;
  text-align: center;
  text-decoration: none;
  font-size: 16px;
}
#twitter-link {
  background-color: red;
}
<div id="quote-box">
  <div id="quote-btn-div">
    <button id="quote-btn">New Quote</button>
    <a id="twitter-link">Twitter link</a>
  </div>
</div>

对不起,如果这是一个愚蠢的问题,我还在学习。

【问题讨论】:

  • 你想把链接放到哪里?你的意思是水平居中吗?最简单的方法可能是将 twitter 链接移到其他地方,特别是因为父 div 是 #quote-btn-div

标签: html css hyperlink flexbox centering


【解决方案1】:

line-height 通常用于将单行文本垂直居中。由于您在按钮上设置了高度,请将 line-height 设置为该值。

#twitter-link { line-height: 100px; }

#quote-btn-div {
  display: flex;
}
#quote-btn,
#twitter-link {
  background-color: #999;
  /* Green */
  border: none;
  width: 300px;
  height: 100px;
  margin: 0 auto;
  color: white;
  text-align: center;
  text-decoration: none;
  font-size: 16px;
}
#twitter-link {
  background-color: red;
  line-height: 100px;
}
<div id="quote-box">
  <div id="quote-btn-div">
    <button id="quote-btn">New Quote</button>
    <a id="twitter-link">Twitter link</a>
  </div>
</div>

【讨论】:

    【解决方案2】:
    #twitter-link {
      line-height: 100px;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-13
      • 2020-12-16
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 2015-04-05
      • 2018-07-25
      相关资源
      最近更新 更多