简体   繁体   English

如何将文本垂直对齐到列表的中间

[英]How to vertically align text to the middle of a list

How can I vertically center text in a list? 如何在列表中垂直居中放置文本? I've tried many ways, as you can see, however, nothing seems to work. 如您所见,我已经尝试了许多方法,但是似乎没有任何效果。

Here's the JSFiddle 这是JSFiddle

And here is the CSS: 这是CSS:

ul.nav {
    border:1px solid #ccc;
    border-width:1px 0;
    list-style:none;
    margin:0;
    padding:0;
    text-align:center;
    width: 100%;
    display: table; 
    table-layout: fixed;
    vertical-align: middle;
    height: 100px;
    vertical-align:middle;
}
/* this styles each link when the mouse is NOT hovered over */
li.nav {
  display: table-cell;
  vertical-align: middle;
  height:100%;
  align-items: center;
  vertical-align:middle;
}

li a {
    display:block;
    height:100%;
    width:100%;
    text-decoration:none;
    vertical-align: middle;
    align-items: center;
    vertical-align:middle;
}

li a:hover {
    background-color: #0099FF;
    color:White;
    vertical-align: middle;
    height:100%;
    align-items: center;
    vertical-align:middle;
}

And HTML: 和HTML:

<ul class="nav">
<li class="nav"><a href="#home">Home</a></li>
<li class="nav"><a href="#news">News</a></li>
<li class="nav"><a href="#contact">Contact</a></li>
<li class="nav"><a href="#about">About</a></li>
</ul>

I just want to get the text completely centered, but no matter what I try, it always seems to stay at the top. 我只想让文本完全居中,但是无论我尝试什么,它似乎总是位于顶部。

One simple way to vertically align your text is to set line-height:100px on your list items. 一种垂直对齐文本的简单方法是在列表项上设置line-height:100px

jsFiddle example jsFiddle示例

li.nav {
    display: table-cell;
    vertical-align: middle;
    height:100%;
    align-items: center;
    vertical-align:middle;
    line-height:100px;
}

Or , remove the display:block rule from your links (no line-height change here) 或者 ,从链接中删除display:block规则(此处行高不变)

jsFiddle example jsFiddle示例

Note that for the second option, you'd have to tweak the link's padding if you want the link to take up more room. 请注意,对于第二个选项,如果希望链接占用更多空间,则必须调整链接的填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM