2011-07-15 28 views

回答

1

假设你知道图像的高度,用top: 50%绝对定位它,并将图像高度的一半作为上边距。因此,对于100x100图像:

div.imgContainer 
{ 
    position: relative; 
} 
div.imgContainer > img 
{ 
    position: absolute; 
    top: 50%; 
    margin-top: -50px; 
    left: 50%; 
    margin-left: -50px; 
} 
3

动态垂直居中有两个选项。

  1. 您可以使用Javascript来获取元素的高度,然后做一些数学运算来将元素的顶部设置为父元素的高度的一半减去元素的一半。
  2. 您使用display: table和百分比来使它正确对齐,如this article所示。

我也有一些运气line-heightvertical-align,但那不是动态的。

0

有一招用的line-height这样做:

<div style=" 
height: /*div height in px here */ px; 
line-height: /*div height in px here */ px; 
text-align:center;"> 

<img src="URL" style="vertical-align:middle;" /> 

</div> 
3

位置为中心长期以来一直是CSS的问题。以上所有建议均有效,但其中每一个都有一点点黑客感觉。如果你不需要支持IE或者Opera,开始使用HTML5灵活盒模型这是真棒:http://www.html5rocks.com/en/tutorials/flexbox/quick/

.centerbox { 
    /* basic styling */ 
    width: 350px; 
    height: 95px; 
    font-size: 14px; 
    border: 1px solid #555; 
    background : #CFC; 

    /* flexbox, por favor */ 
    display: -webkit-box; 
    -webkit-box-orient: horizontal; 
    -webkit-box-pack: center; 
    -webkit-box-align: center; 

    display: -moz-box; 
    -moz-box-orient: horizontal; 
    -moz-box-pack: center; 
    -moz-box-align: center; 

    display: box; 
    box-orient: horizontal; 
    box-pack: center; 
    box-align: center; 
}