我将一个元素垂直和水平居中。一切正常,除了一个问题:我可以在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; }
小提琴:
此外:
谢谢!
答案 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
。