将<a>元素中的文本与CSS垂直对齐

mic*_*urk 16 html css vertical-alignment

有人可以解释我如何垂直对齐<a>元素中的文本- 所以两个文本都出现在红色框的中间?

http://jsfiddle.net/WeKtX/

这是我的HTML:

<ul>
<li><a href="#">this is a link</a></li>
<li><a href="#">this is an even longer link</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

和我的CSS:

li {list-style-type:none;margin:0;padding:0}
li a {width:100px;float:left;background:red;margin-right:20px;height:40px}
Run Code Online (Sandbox Code Playgroud)

非常感谢任何指针

cer*_*eny 14

如果要将文本水平居中,请尝试:

text-align: center;
Run Code Online (Sandbox Code Playgroud)

如果要将文本垂直居中,请尝试:

line-height: 40px; //Where 40px is the height of your parent element
Run Code Online (Sandbox Code Playgroud)

请记住,使用行高时,它只能在一行文本上工作.如果你想做多行文本,那么我担心你必须指定文本的高度,然后在父元素上使用position: absolute;文本position: relative;.

对于你的多行示例,我会尝试类似下面的jsFiddle:

li {
    list-style-type:none;
    margin:0;
    padding:0;
    position: relative;
    height: 60px;
    width: 200px;
    display: block;
    background:red;
}

li a {
    width:100px;
    height:40px;
    position: absolute;
    top: 50%;
    margin-top: -20px;
}
Run Code Online (Sandbox Code Playgroud)