样式为:
.innerdiv{
display: inline-block;
vertical-align: middle;
width: 300px;
}
.outerdiv{
text-align: center;
background: #c0c0c0;
}
.outerdiv .before,.outerdiv:before {
content: '';
display: inline-block;
/**display: inline;*/
height: 100%;
vertical-align: middle;
margin-right: -0.25em;
}
HTML:
<div style="height:500px" class="outerdiv">
<div class="innerdiv">
<span class="" style="font-size:26px">Hello </span>
<br/>
<img style="width:150px" src="http://mrsdalesworkspace.pbworks.com/f/1302032618/desert(1).jpg"/>
</div>
我想使内部div相对于外部div在水平和垂直方向居中,上面的代码在除IE7之外的任何地方都能很好地工作。
我认为由于"before"伪类的存在,它在IE7中不起作用。
我试着用修复它
样式为:
.outerdiv{
text-align: center;
background: #c0c0c0;
*zoom: expression(
this.runtimeStyle.zoom="1",
this.appendChild( document.createElement("small") ).className="after",
this.insertBefore( document.createElement("small"), this.firstChild ).className="before"
);
}
.outerdiv .before,.outerdiv:before {
content: '';
display: inline-block;
/**display: inline;*/
height: 100%;
vertical-align: middle;
margin-right: -0.25em;
}
我用这个也做不到。
我甚至尝试使用插件
<!--[if lt IE 8]>
<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE8.js"></script>
<![endif]-->
以及
<script type="text/javascript" src="http://jquery.lukelutman.com/plugins/pseudo/jquery.pseudo.js"></script>
它仍然没有起作用。
我知道使用position:absolute
并设置上下边距和位置可以实现它。我想使用伪类来实现它。
这应该适用于所有浏览器:
.outerdiv {
position:relative;
}
.outerdiv .innerdiv {
position:absolute;
top:50%;
left:50%;
width:200px;
height:200px;
margin-top:-100px; // height / 2
margin-left:-100px; // width /2
}
IE7根本不理解::before
和::after
。
这意味着它也不理解.outerdiv .before,.outerdiv:before
组合选择器。你应该把它们分开。
你可以试试这个类:
.center {
position: absolute; /* do not change */
top: 50%; /* do not change */
left: 50%; /* do not change */
width: 80%; /* 80% of the parent's width. Of course, you can change this value. */
height: 80%; /* 80% of the parent's width. Of course, you can change this value. */
margin-top: -40%; /* current height / 2 */
margin-left: -40%; /* current width / 2 */
}
codepen.io 示例