DIV撑满剩余高度,未知高度垂直居中

css3 transform:translateY 未知垂直水平居中

// 相对于父组件进行绝对定位,top 50%, 再 用CSS3属性 transform: translateY(-50%) 设置Y轴-50%即可

parentElement{
        position:relative;
    }

 childElement{
    width: 200px;
    height: 209px;
    background: red;
    position: absolute;
    left: 50%;
    transform: translate(-50%,-50%);
    top: 50%;

 }

 

DIV撑满剩余高度

方法一:绝对定位

<style> 

    #box{
        background:black;
        height:600px;
        position: relative;
    }

    #uncle{
        background: blue;
        height: 200px;
        width:100%
    }

	#father{
         // 父级box需要相对定位,要撑满的div部分用绝对定位,和top,bottom固定视口,width100%撑满剩下的部分
        background: red;
        width:100%;
        position:absolute;
        top:200px;
        bottom:0;  
    }
 	#son{
        position: absolute;
        top: 50%;
        left:50%;
        transform: translateY(-50%);
 		background:yellow;
        transform: translateX(-50%)
 	}

</style>
<body>
    <div id="box">
        <div id="uncle">固定内容</div>
        <div id="father">要撑满全部高度的DIV
            <div id="son">未知高度要垂直居中,水平居中的内容</div>
        </div>
    </div>
</body>

注:Position:absolute是相对于他最近一个祖先节点定位,该祖先节点必须有postion:absolute,  relative,  fixed 的属性,如若没有,就相对于body做绝对定位

方法二:浮动

<style>
		.parent {
			height: 500px;
			width: 300px;
			border: 1px solid red;/***/
			padding: 2px 2px;/***/
		}
		
		.nav {
			height: 100px;
			width: 100%;/*必须沾满宽度防止浮动*/
			float: left;/*必须*/
			background-color: red;
		}
		
		.content {
			height:100%;/*必须*/
			background-color: green;
		}
	</style>
 
	<body>
		
		<div class="parent">
			<div class="nav">
				固定高度
			</div>
			<div class="content">
				自适应父容器, 充满剩余的空间 
			</div>
		</div>
 
	</body>

上面的 div浮动,下面的DIV自动会填上,并设置为height:100%就OK


版权声明:本文为chose_DoIt原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。