换肤

垂直居中的几种常用方法

实现垂直居中的几种常用方法

1. translateY(-50%)实现垂直居中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
       .content{
	 	width:100%;
	 	height:300px;
	 	background: #eee
	 }
	 .juzhong{
	 	width:200px;
		position: absolute;
		top:50%;
		background:pink;
		transform: translateY(-50%);
	 }
    </style>
</head>
<body>
    <div class="content">
		<div class="juzhong"></div>
	</div>
</body>
</html>

2. 不考虑IE10以下兼容的话可以用flex布局

   .content{
	 	width:100%;
	 	height:300px;
		display:flex;
	    display: -webkit-flex; 
	    align-items:center;
	 	background: #eee
	 }
 .juzhong{
	 	width:200px;
		background:pink;
	 }	 
	 

3. 将元素变成行内元素,在父元素中用line-height:父元素高度;

.content{
	 	width:100%;
	 	height:300px;
		text-align: center;/*让文本水平居中*/
	 	background: #eee;
	 	line-height:300px;
	 }
	 .juzhong{
	 	display: inline-block;
	 	width:200px;
	 	height:200px;
		background:pink;
		line-height: 200px;
	 }

posted @ 2018-01-16 15:20  cyonline  阅读(121)  评论(0)    收藏  举报