可以居中图像但不能在IE7中居div

时间:2013-01-01 16:57:05

标签: javascript jquery html css internet-explorer-7

我将一个元素垂直和水平居中。一切正常,除了一个问题:我可以在IE7中垂直居中img,但我无法居中div。 IE适用于图像的样式,不适用于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的大小,因为它包含动态内容

谢谢!

1 个答案:

答案 0 :(得分: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/