百分比高度DIV如何垂直居中

来源:互联网 发布:openstack cinder 源码 编辑:程序博客网 时间:2024/04/29 21:54

问题:

如何使百分比高度子DIV在父元素中居中?

思路如下:

引入一个中间DIV,使DIV成为目标DIV的父元素(即嵌套加深一层),且相对于目标DIV原本父元素 top:50%;   ,然后再对目标DIV相对中间DIV width:100%;height:100%;top:-50%;   ,即可完成垂直居中

HTML代码如下:

<div id="box"><div id="innerBox"><div id="container"></div></div></div>

CSS代码如下:

#box{width: 30%;height:300px;margin:0 auto;border:1px solid #000;}#innerBox{position: relative;width:30%;height:30%;left: 50%;top:50%;}#container{position: absolute;border:1px solid #000;width: 100%;height: 100%;top:-50%;left:-50%;}

效果如下:


测试中我让目标DIV也顺便水平居中了。

——————转载请注明出处





0 0