代码之家  ›  专栏  ›  技术社区  ›  michaelmcgurk

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

  •  16
  • michaelmcgurk  · 技术社区  · 13 年前

    有人能解释一下我是如何将文本垂直对齐的吗 <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>
    

    和我的 CSS格式 :

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

    非常感谢您的指点

    1 回复  |  直到 11 年前
        1
  •  14
  •   cereallarceny    13 年前

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

    text-align: center;
    

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

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

    请记住,当使用线条高度时,它只适用于 单线 的文本。如果你想做多行文本,那么恐怕你必须指定文本的高度,然后使用 position: absolute; 关于文本 position: relative; 在父元素上。

    对于你的多行示例,我会尝试如下 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;
    }