2011-11-21 49 views
-3

我有绝对定位div,我不得不垂直居中他的内容。任何解决方案垂直居中在绝对格

更新: 我的内容是旋转(通过css3)图像,并且此图像已经水平定位。

<div style="width:200px;height:100px;background:black;position:absolute;"> 
     <img src="a.png" style="width:100px;-webkit-transform: rotate(45deg);margin-left:auto;margin-right:auto; display:block"/> 
    </div> 
+3

您必须提供有关内容的更多详细信息。它是一行文本吗?你知道内容的高度吗?还是那个容器? – deviousdodo

+0

我确实发布了更新。 – galer88

回答

0

dh = your div's height
yourDiv.style.top = window.innerHeight/2-dh/2

这是最大你去给没有细节。

编辑:在知道内容是图像之后。

第一个的方式,如果你知道这两个高度,div的和img已经。

<div style="width:200px;height:200px;background:black;position:absolute;"> 
     <img src="a.png" style="width:100px;-webkit-transform: rotate(45deg);margin-left:auto;margin-right:auto; display:block"/> 
    </div>​ 

和风格的图像

img{margin-top:23%;}​ 

拨弄去用它:http://jsfiddle.net/DZBp8/

第二方式:一些jQuery的,因为我已经回答了。 HTML: 的jQuery:

var dh = $('#container').height(); 
var ih = $('img').height(); 
$('img').css('margin-top',(dh-ih)/2+'px'); 

http://jsfiddle.net/DZBp8/1/

+0

oops。这是JavaScript。 – 2011-11-21 08:38:17

+0

添加了详细信息。请让我知道如果这不行。没有什么我比星期五晚上更喜欢寻找解决方案。 – 2012-04-13 14:59:45

0

这可能会实现:

<!-- This method is for for modern browsers only --> 
<html> 
<head> 
<title>Vertical Centering</title> 
<style> 
.parent { 
    display: table; 
    height: 400px; 
    width: 400px; 
    background-color: green; 
} 
.content { 
    display: table-cell; 
    vertical-align: middle; 
} 
</style> 
</head> 
<body> 
<div class="parent"> 
<div class="content"> 
     This content will be vertically centered in the parent element. 
</div> 
</div> 
</body> 
</html> 

Working example at jsfiddle。您可以解决它并获得解决方案。希望这可以帮助。