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

问题:

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

思路如下:

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

HTML代码如下:

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


CSS代码如下:

#box{
	 30%;
	height:300px;
	margin:0 auto;
	border:1px solid #000;

}
#innerBox{
	position: relative;
	30%;
	height:30%;
	left: 50%;
	top:50%;
}
#container{
	position: absolute;
	border:1px solid #000;
	 100%;
	height: 100%;
	top:-50%;
	left:-50%;
}


效果如下:


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

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





原文地址:https://www.cnblogs.com/jiangmy/p/4515419.html