使一个div水平垂直居中的方法

1,404

在工作中,经常会碰到让一个div垂直水平居中。

方法一:

使用绝对定位:不确定div的宽度和高度时,采用 transform: translate(-50%, -50%);当前div的父级添加position:(relative/absolute/fixed)

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		*{
			margin: 0;
			padding: 0;
			box-sizing: border-box;
		}
		.overlay {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.7);
		}
		.popup {
			position: absolute; /* 绝对定位 */
			top: 50%;
			left: 50%;
			/* 
				确定宽高时使用 
				width: 200px;
				height: 200px;
				左偏移宽度的一半,上偏移宽度的一半 
				margin-left: -100px;
				margin-top: -100px;
			*/
			/* 不确定宽高使用 */
			transform: translate3d(-50%, -50%, 0);
			padding: 20px;
			overflow-y: auto;
			border-radius: 4px;
			background-color: #fff;
			transition: transform 0.3;
		}
	</style>
</head>
<body>
	<div>
		这个一个静态页面
	</div>
	<div class="overlay">
		<div class="popup">div垂直水平居中</div>
	</div>
</body>
</html>

方法二:

使用flex布局:当前div父级
display: flex;
justify-content: center;
align-items: center;

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		*{
			margin: 0;
			padding: 0;
			box-sizing: border-box;
		}
		.overlay {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.7);

			display: flex;
			justify-content: center; /* 水平居中 */
			align-items: center; /* 垂直居中 */
		}
		.popup {
			padding: 20px;
			overflow-y: auto;
			border-radius: 4px;
			background-color: #fff;
		}
	</style>
</head>
<body>
	<div>
		这个一个静态页面
	</div>
	<div class="overlay">
		<div class="popup">div垂直水平居中</div>
	</div>
</body>
</html>

方法三:

使用绝对定位方法:
当前div
top right bottom left 都设置为0
margin: auto;
设置宽高

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		*{
			margin: 0;
			padding: 0;
			box-sizing: border-box;
		}
		.overlay {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.7);
		}
		.popup {
			position: absolute;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;

			margin: auto; /* 必须设置margin: auto; */
			width: 200px; /* 必须设置宽高 */
			height: 200px;

			padding: 20px;
			overflow-y: auto;
			border-radius: 4px;
			background-color: #fff;
		}
	</style>
</head>
<body>
	<div>
		这个一个静态页面
	</div>
	<div class="overlay">
		<div class="popup">div垂直水平居中</div>
	</div>
</body>
</html>