0

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

谢谢!

4

1 回答 1

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/

于 2013-01-01T17:07:49.470 回答