css设置垂直居中的方法

(1)父元素设置display:table;子元素设置display:table-cell;vertical-align:middle;缺点:ie8以下不支持。

<!doctype html>
<html>
<head>
	<style>
		#wrapper {
    		display: table;
    		height:200px;
		}

		#cell {
		    display: table-cell;
		    vertical-align: middle;
		}
	</style>
</head>
<body>
	<div id="wrapper">  
	    <div id="cell">Content goes here</div>
	</div> 
</body>
</html>

(2)元素的宽高一定,设置为绝对定位,top:50%;margin-top等于负的元素高度的一半.

<!doctype html>
<html>
<head>
	<style>
		#wrapper{
			position:absolute;
			top:50%;
			left:50%;
			margin-top:-100px;
			margin-left:-100px;
			width:200px;
			height:200px;
			background:maroon;
		}
	</style>
</head>
<body>
	<div id="wrapper">  
	</div> 
</body>
</html>

(3)元素的宽高一定,设置为绝对定位,top:0;bottom:0;margin:auto;

<!doctype html>
<html>
<head>
	<style>
		#wrapper{
			position:absolute;
			top:0;
			bottom:0;
			margin:auto;
			width:200px;
			height:200px;
			background:maroon;
		}
	</style>
</head>
<body>
	<div id="wrapper">  
	</div> 
</body>
</html>

(4)只能将等行文本垂直居中,设置height和line-height相等就好。

(5)flex布局实现垂直居中

<!doctype html>
<html>
<head>
	<style>
	#wrapper{
		display: flex;
	    justify-content:center;
	    align-items:center;
	    background:maroon;
	    width:100px;
	    height:100px;
	}
	</style>
</head>
<body>
	<div id="wrapper"> 
		<div id="content">center</div>
	</div> 
</body>
</html>

(6)给content前面加一个同级元素,并且设置height:50%;margin-bottom等于负的contentHeight的一半,float:left;content清除浮动,content就可以垂直居中显示。

<!doctype html>
<html>
<head>
	<style>
	#wrapper{
	  width:400px;
	  height:400px;
	  border:1px solid #000;
	}
	.floater {
    float:left; 
    height:50%; 
    margin-bottom:-120px;
	}
	#content {
    clear:both; 
    height:240px; 
    position:relative;
    background:maroon;
	}
	</style>
</head>
<body>
	<div id="wrapper"> 
		<div class="floater"></div>  
		<div id="content"></div>
	</div> 
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值