块级元素水平垂直居中问题

关于块级元素水平居中的方法总结,
效果图:在这里插入图片描述

方法一:父元素dispaly:flex;
子元素margin: auto;

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>块级元素水平垂直居中</title>
	<style>
		/* 样式 */
		html, body {
			height: 100%;
		}
		.father {
			height: 100%;
			background: teal;
		}
		.son {
			width: 300px;
			height: 300px;
			background: orange;
		}
		span {
			background: green;
		}
		/* 水平垂直居中 */

		/* 方法一 */
		 .father {
			display: flex;
		}
		.son {
			margin: auto;
		} 
</style>
</head>
<body>
	<div class="father">
		<div class="son"></div>
	</div>
</body>
</html>

方法二:
父元素:
display: flex;
align-items: center;
justify-content: center;

 .father {
			display: flex;
			align-items: center;
			justify-content: center;
		} 

方法三:
父元素:position: relative;
子元素:
position: absolute;
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -150px;

 .father {
			position: relative;
		}
		.son {
			position: absolute;
			top: 50%;
			left: 50%;
			margin-top: -150px;
			margin-left: -150px;
		} 

方法四:
父元素:
position: relative;
子元素:
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;

.father {
			position: relative;
		}
		.son {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			margin: auto;
			}

猜你喜欢

转载自blog.csdn.net/weixin_45852958/article/details/107822537