div內容垂直居中對齊

css垂直居中屬性設置vertical-align: middle對div不起做用,例如:css

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Commpatible" content="IE=edge">
<title>DIV垂直居中對齊</title>
<style type="text/css">
* {
	margin: 0;
	padding: 0;
}

html, body {
	width: 100%;
	height: 100%;
}

body {text-align: center; vertical-align: middle;}
.outer {
	width: 400px;
	height: 120px;
	position: relative;
	left: 20px;
	top: 20px;
	text-align: center;
	vertical-align: middle;
	border: 1px dashed blue;
}

.button {
	width: 200px;
	height: 40px;
}
</style>
</head>
<body>
	<div class='outer'>
		<button class='button'>在DIV中垂直居中</button>
	</div>
</body>
</html>

運行後按鈕沒有在DIV中垂直居中

解決思路:若是div和按鈕的寬高都肯定爲具體像素值,能夠直接設定按鈕的css屬性:position:relative; top爲(div.height - button.height)/2,left爲(div.width-button.height)/2;不然給按鈕添加一個div父元素,寬高和按鈕相同,position設定爲relative,top和left都爲50%(即左上角位置設定在外層div的中心),再將按鈕左上角位置座標設定爲父元素div寬高(也等於按鈕自身寬高)的-50%html

詳細代碼以下:ui

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Commpatible" content="IE=edge">
<title>DIV垂直居中對齊</title>
<style type="text/css">
* {
	margin: 0;
	padding: 0;
}

html, body {
	width: 100%;
	height: 100%;
}

body {text-align: center; vertical-align: middle;}
.outer {
	width: 400px;/* 或者爲百分比 */
	height: 120px;
	position: relative;
	left: 20px;
	top: 20px;
	border: 1px dashed blue;
}

.inner {
	width: 200px;
	height: 40px;
	position: relative;
	position: relative;
	top: 50%;
	left: 50%;
}

.button {
	width: 200px;
	height: 40px;
	position: relative;
	top: -50%;
	left: -50%;
}
</style>
</head>
<body>
	<div class='outer'>
		<div class='inner'>
			<button class='button'>在DIV中垂直居中</button>
		</div>
	</div>
</body>
</html>

再次運行後,div中按鈕上下居中顯示

END
3d