使用transfrom实现元素居中显示,行级元素,块级元素居中显示。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>transform: 实现任意元素居中</title>
		<!-- 行级元素:text-align:center
		 块级元素:margin:0 auto; -->
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}
			.box {
				width: 400px;
				height: 400px;
				border-radius: 200px;
				background-color: #ccc;
				margin: 100px auto;
				position: relative;
			}
			.rec {
				width: 100px;
				height: 100px;
				position: absolute;
				background-color: red;
				/* 定位的百分比,是参照父容器,偏移50% */
				left: 50%;
				top: 50%;
				/* 使用transform实现元素的居中(这里的百分比,是参照元素本身的宽高) 
				不建议写具体的数值50px,建议使用百分比实现。*/
				transform:translate(-50%, -50%)
			}
		</style>
	</head>
	<body>
		<div class="box">
			<div class="rec"></div>
		</div>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/xqiitan/article/details/88353950