2013-01-01 41 views
0

我正在垂直和水平居中放置一个元素。一切工作正常,除了一个问题:我可以在IE7垂直中心img,但我不能集中div。什么风格IE适用于图像,不适用于div?可以在IE7中居中但不能居中div

HTML

<!-- image - works correctly --> 
<div class="container"> 
    <img class="inner" src="http://placekitten.com/200/200?image=2" /> 
</div> 
<br/> 
<!-- div - doesn't work (aligned to top) --> 
<div class="container"> 
    <div class="inner">123</div> 
</div> 

CSS:

.container { 
    height: 300px; 

    background: #EEE; 
    text-align: center; 
    line-height: 300px; 
} 

.inner { vertical-align: middle; width: 100px; 
height: 100px; background:red; display: inline-block; line-height: 1.3; }​ 

小提琴:

http://jsfiddle.net/kpdxu/7/

另外:

  • 我不知道的DIV
  • 我可以使用JavaScript大小,但因为它含有动态内容

谢谢你,我不能得到DIV的大小!

+0

在IE7,'直列block'仅支持那些自然联元素,因此,不上的DIV。您可以使用'margin:auto'将块元素(如DIV)居中。 –

+0

我可能读错了,但我认为他们正在寻找一种垂直对齐div的方法。 – gotohales

+0

@ŠimeVidas谢谢,完全忘了这一点。 – Marvin3

回答

1

使用本css

.container { 
    height: 300px; 
    background: #EEE; 
    text-align: center; 
    line-height: 300px; 
    position:relative; //<--this will hold the absolute positioned elements 
} 

.inner { 
    vertical-align: middle; 
    width: auto; 
    height: auto; 
    background:red; 
    display: block; // <--display block will do for ie 7 
} 
通过jQuery

$.fn.center = function() { 
    this.css("position","absolute"); 
    this.css("top", ($('.container').height() - this.height())/2 + "px"); 
    this.css("left", ($('.container').width() - this.width())/2 + "px"); 
    return this; 
} 

然后使用它像这样

$('.inner').each(function(){ 
    $(this).center(); 
}); 

但父母必须是position relative

结帐小提琴:http://jsfiddle.net/kpdxu/14/

+0

你对代码做了什么改变? –

+0

刚刚更新了答案和评论。 – Jai

+0

@JA不幸的是,它不是一个选项,因为元素的大小是动态的,可以是任何东西。 – Marvin3