css垂直居中的几种方法

1、单行文本居中

html

<p>content</p>

css

p {
	height: 30px;
	line-height: 30px;
}

要点:heightline-height值保持一致

用处: button、图片、单行文本内容居中

局限:无法用于多行元素

2、div容器固定高度居中

html

<div id="wrapper">
	<div class="container">
		<p>first paragraph</p>
		<p>second paragraph</p>
	</div>
</div>

css

#wrapper {
	height: 200px;
	 300px;
	background: #ccc;
	position: relative;
}
.container {
	height: 100px;
	 200px;
	position: absolute;
	top: 50%;
	left: 50%;
	margin-top: -50px;		//height的一半
	margin-left: -100px;		//width的一半
	background: #f00;
}

如图

要点:给要居中的容器设置position: absolutetop: 50%margin-top: -height/2(即高度的一半)(水平居中同上)

用处: 多行元素居中对齐,用于页面在最中间的布局

局限:需要固定的高度(即大小要确定)、父元素需要相对定位;当内容大于height时,内容溢出,无法居中;如果overflow:auto,会出现滚动条,如果overflow:hidden,内容被切断

3、模拟表格居中

html

<div id="wrapper">
	<div class="container">
		<p>first paragraph</p>
		<p>second paragraph</p>
	</div>
</div>

css

#wrapper {
	height: 200px;
	display: table;
	background-color: #f00;
}
.container {
	display: table-cell;
	vertical-align: middle;
}

如图

要点:父元素display: table,当前元素display: table-cell,并设置vertical-align: middle

用处:用于高度可以随内容动态改变

局限:不支持IE6-7

4、容器前添加空div

html

<div id="wrapper">
	<div class="empty"></div>
	<div class="container"></div>
</div>

css

#wrapper {
	height: 200px;
	background-color: #ccc;
}
.empty {
	height: 50%;			//相对于父元素的一半
	margin-bottom: -50px;	//.container的height的一半
}
.container {		
	height: 100px;
	background-color: #f00;
}

如图

要点:在容器前添加空div,并为其设置height: 50%(父元素高度一半),margin-bottom为容器高度一半

用处和局限同方法2

原文地址:https://www.cnblogs.com/u14e/p/5289984.html