垂直对齐< a>中的文字元素与CSS [英] Vertically align text in <a> element with CSS

查看:88
本文介绍了垂直对齐< a>中的文字元素与CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



http://jsfiddle.net/WeKtX/

这是我的 HTML

 < ul> 
< li>< a href =#>这是一个连结< / a>< / li>
< li>< a href =#>这是一个更长的链接< / a>< / li>
< / ul>

和我的 CSS

  li {list-style-type:none; margin:0; padding:0} 
li a {width:100px; float:left; background:red ; margin-right:20px; height:40px}

非常感谢任何指针

解决方案

如果您想将文本横向居中,请尝试:

  text-align:center; 

如果您想垂直居中文本,请尝试:

  line-height:40px; // 40px是父元素的高度

请记住,当使用line-height ,它只能在一行文本中使用。如果你想做多行文本,那么恐怕你必须指定文本的高度,然后使用 position:absolute; 对文本加上<$ c

对于你的多行示例,我会尝试一些类似于 http://jsfiddle.net/WeKtX/10/\">以下jsFiddle

  li {
list-style-type:none;
保证金:0;
padding:0;
职位:亲属;
height:60px;
width:200px;
display:block;
背景:红色;
}

li a {
width:100px;
height:40px;
位置:绝对;
top:50%;
margin-top:-20px;
}


Can someone explain how I vertically align the text in <a> elements - so both text appears in the middle of the red box?

http://jsfiddle.net/WeKtX/

Here's my HTML:

<ul>
<li><a href="#">this is a link</a></li>
<li><a href="#">this is an even longer link</a></li>
</ul>

and my CSS:

li {list-style-type:none;margin:0;padding:0}
li a {width:100px;float:left;background:red;margin-right:20px;height:40px}

Many thanks for any pointers

解决方案

If you want to center the text horizontally then try:

text-align: center;

If you want to center the text vertically then try:

line-height: 40px; //Where 40px is the height of your parent element

Keep in mind, that when using line-height, it will only work on one line of text. If you want to do multiple lines of text then I'm afraid you have to specify a height to the text and then use position: absolute; on the text with position: relative; on the parent element.

For your multi-line example I'd try something like the following 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;
}

这篇关于垂直对齐&lt; a&gt;中的文字元素与CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆