Html 将 div 中的链接垂直居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11019186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:00:50  来源:igfitidea点击:

Vertically center a link within a div

htmlcss

提问by Hymanie

I have an unordered list...

我有一个无序列表...

<ul class="hide">
  <li class="home">
    <div class="link">
      <a href="/">Home</a>
    </div>
  </li>
  <li class="about">
    <div class="link">
      <a href="/about">About Our Community</a>
    </div>
  </li>
  <li class="contact">
    <div class="link">
      <a href="/contact">Contact Us</a>
    </div>
  </li>
</ul>

My CSS looks like this....

我的 CSS 看起来像这样....

#sitenav ul li .link a {
  color: #555;
  text-decoration: none;
  float: left;
  padding-right: 3px;
  margin-top: auto;
  margin-bottom: auto;
}

But the margins do not center the link vertically

但边距不会垂直居中链接

Any ideas?

有任何想法吗?

回答by Luis

This solution could work for you: http://jsfiddle.net/WLQAS/8/

这个解决方案可以为你工作:http: //jsfiddle.net/WLQAS/8/

margin-top: auto;and margin-bottom: auto;don't work to align vertically the objects.

margin-top: auto;并且margin-bottom: auto;不要垂直对齐对象。

Updated CSS

更新的 CSS

li {
  color: #555;
  text-decoration: none;
  float: left;
  padding-right: 3px;    
}

.link {
    vertical-align: middle;
    display: table-cell;
    height: 50px;
}

回答by doptrois

Here's a cross browser compatible solution for vertical aligning an a-element with an unknown height within a div:

这是一个跨浏览器兼容的解决方案,用于a在 a 中垂直对齐具有未知高度的 -元素div

Workswith link texts with and without line-breaks.

适用于带和不带换行符的链接文本。

CSS

CSS

* { margin: 0; padding: 0 }

ul {}
ul li {
    display: table;
    height: 75px;
    #position: relative; /* ie hack */
    overflow: hidden;
    border: 1px solid red;
}

ul li div {
    #position: absolute; /* ie hack */
    #top: 50%; /* ie hack */
    display: table-cell;
    vertical-align: middle;
}

ul li div a {
    #position: relative; /* ie hack */
    #top: -50%; /* ie hack */
    border: 1px solid green
}

It's not recommended to use CSS hacks here, use conditional commentsinstead.

不建议在这里使用 CSS hacks,而是使用条件注释

Live demo: http://jsfiddle.net/ahdzg/1/
More infos about this trick: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

现场演示http: //jsfiddle.net/ahdzg/1/
关于这个技巧的更多信息http: //www.jakpsatweb.cz/css/css-vertical-center-solution.html

Hope this helps. Otherwise feel free to ask.

希望这可以帮助。否则请随意询问。

回答by Daniel Msanii

.parent_div{display:table;}.child_div{display:table-cell;vertical-align:middle;}

Then put your link inside the child div.

然后将您的链接放在子 div 中。