【前端】几种实现水平垂直居中的方法总结

实现代码:

<!DOCTYPE html>
<html>
<head>
	<title>垂直居中</title>
	<meta charset="utf-8">
	<script type="text/javascript"></script>
	<style type="text/css">
		/* 方法 1  子元素 position:absolute 0 0 0 0*/
		#container1{
			width: 400px;
			height: 400px;
			position: relative;
			background-color: #f5f5f5;
		}
		#item1{
			width: 200px;
			height: 200px;
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			margin: auto;
			background-color: #03c03c;
		}
		
		/* 方法 2  子元素 position:absolute*/
		#container2{
			margin-top: 20px;
			width: 400px;
			height: 400px;
			position: relative;
			background-color: #f5f5f5;
		}
		#item2{
			width: 200px;
			height: 200px;
			position: absolute;
			left: 50%;
			margin-left: -100px;
			top: 50%;
			margin-top: -100px;
			background-color: #03c03c;
		}
		
		/* 方法 3 子元素 position:relative*/
		#container3{
			position: relative;
			margin-top: 20px;
			width: 400px;
			height: 400px;
			background-color: #f5f5f5;
		}
		#item3{
			width: 200px;
			height: 200px;
			position: relative;
			left: 50%;
			margin-left: -100px;
			top: 50%;
			margin-top: -100px;
			background-color: #03c03c;
		}
		
		/* 方法 4 line-height*/
		#container4{
			width: 400px;
			height: 400px;
			line-height: 100px;
			background-color: #f5f5f5;
			margin-top: 20px;
		}
		#item4{
			width: 200px;
			height: 200px;
			margin: 0 auto;
			background-color: #03c03c;
		}
		
		/* 方法 5  display:flex*/
		#container5{
			width: 400px;
			height: 400px;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #f5f5f5;
			margin-top: 20px;
		}
		#item5{
			width: 200px;
			height: 200px;
			background-color: #03c03c;

		}
		
		/* 方法 6  display:box; */
		#container6{
			height: 400px;
			width: 400px;
			margin-top: 20px;
			background-color: #f5f5f5;
			display: -webkit-box;
			display: box;
			-webkit-box-align: center;
			-webkit-box-pack: center;
			box-align: center;
			box-pack: center;
		}
		#item6{
			height: 200px;
			width: 200px;
			background-color: #03c03c;
		}
	</style>
</head>
<body>
<div id="container1">CONTAINER1
	<div id="item1">ITEM1</div>
</div>

<div id="container2">CONTAINER2
	<div id="item2">ITEM2</div>
</div>

<div id="container3">CONTAINER3
	<div id="item3">ITEM3</div>
</div>

<div id="container4">CONTAINER4
	<div id="item4">ITEM4</div>
</div>

<div id="container5">
	<div id="item5"></div>
</div>

<div id="container6">
	<div id="item6"></div>
</div>
</body>
</html>

  

 

posted @ 2017-10-18 13:46  Dragonir  阅读(794)  评论(0编辑  收藏  举报