2011-09-30 41 views
8

这个问题的变化已经被问了很多次。垂直居中CSS是一个挑战。如何使用CSS将文本垂直居中在LI内的锚点中?

我有一个特定的场景,处理水平显示的列表。标记是这样的:

<ul id='ul1' class='c'> 
    <li><a href='javascript:void(0)'>Fribble Fromme</a></li> 
    <li><a href='javascript:void(0)'>Fobble</a></li> 
    <li><a href='javascript:void(0)'>Foo Fickle Pickle</a></li> 
    </ul> 

的风格是这样的:

ul.c { 
    height:52px; 
    text-align:center; 
    } 
    ul li a { 
    float:left; 
    text-decoration:none; 
    border: 1px solid Maroon; 
    padding:2px 12px; 
    background:#FFEF8A; 
    line-height:1em; 
    width:100px; 
    } 
    ul li a:hover { 
    background: #CCC; 
    } 
    ul li { 
    height:52px; 
    display:inline-block; 
    } 

结果列表如下:

enter image description here

但我想所有的箱子是高度相同,我希望文本在每个框中垂直居中。我可以通过为A元素添加height样式来设置箱子高度。结果是这样的:

enter image description here

...这是接近我想要的,但垂直居中没有发生。

我可以设置line-height为正文,as suggested in this post,做垂直居中。我甚至可以为不同的A元素选择不同的值line-height,如果我知道哪些元素将获得多行文本。但我不知道哪些需要多行。

当A元素中的某些元素包含文本时,我怎样才能让它居中?

+1

使用令人恐惧的表! –

回答

15

你可以使用display:table等一起vertical-align:middle

ul.c { 
    text-align:center; 
    display:table; 
} 

ul li { 
    float:left;  
} 

ul li a { 
    text-decoration:none; 
    border: 1px solid Maroon; 
    padding:2px 12px; 
    background:#FFEF8A; 
    width:100px; 
    height:52px; 
    display:table-cell; 
    vertical-align:middle; 
} 

ul li a:hover { 
    background: #CCC; 
} 

例子:http://jsfiddle.net/kf52n/2/

0

我想不出在CSS中这样做的方法。我发现我可以用Javascript来做我需要的,在运行时将padding-toppadding-bottom设置为适当的值。该技术是测量A元素的“自然”高度,然后设置填充以使A元素垂直居中。

这里是必要的js代码:

function setHeightIntelligently(ulElement) { 
    var items, L1, i, anchor, availableHeight = ulElement.clientHeight, 
     naturalHeight, pad; 
    items = ulElement.children; 
    for(i=0, L1 = items.length;i<L1;i++){ 
     if (items[i].tagName.toUpperCase() == 'LI') { 
     anchor = items[i].children[0]; 
     naturalHeight = anchor.clientHeight; 
     pad = (availableHeight - naturalHeight)/2; 
     anchor.style.paddingTop= pad+'px'; 
     anchor.style.paddingBottom= pad+'px'; 
     } 
    } 
    } 

    function init() { 
    var element = document.getElementById('ul1'); 
    setHeightIntelligently(element); 
    } 

在CSS,必须没有明确设置高度或填充的A元素。这样做会导致“自然”高度不是我们所需要的。

的结果是这样的:

enter image description here

要看到它的行动,go here

+0

干得好!你有jQuery的等价物吗? – Mike6679

-1
在您设定的高度,行高为相同的CSS

。然后你会得到一个矩形框。

但你仍然看到在底部空间的原因是由于填充

在填充添加两个值增加了顶部和底部填充

边距:顶底;

,因为它是2和12,你看到了巨大的空间。

试试这个

height: 52px; 
line-height:52px; 
padding: 6px 6px; // here you have to tweak and see the output 
vertical-align:center; 

让我知道这是工作

2

老问题,但答案现在可以Flexbox的更新。

a { 
    height: 60px; 
    display: flex; 
    align-items: center; 
    justify-content: center; 
} 
+0

非常好,正是我在找的东西。谢谢。 – Christof