css 利用 position + transform 实现弹性盒子横向纵向居中

前端常有"横竖居中"的需求, 固定宽高的还好办
遇到宽高不确定的情况, 我向大家推荐下面这个方法

原理其实就两点

  • position: absolute; 的百分百参照父元素
  • transform: translate(-50%, -50%); 的百分百参照当前元素

position 和 transform 合起来的效果就是把父元素和当前元素的中点对齐, 从而达到居中的效果

demo

<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta charset="utf-8">
	<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
	<title>css 利用 transform 实现横向纵向居中</title>
	<style>
		.father {
     
     
			width: 300px;
			height: 300px;
			background-color: #33A8F5;
			position: relative;
		}

		.son {
     
     
			/* 自定义宽高 */
			width: auto;
			height: auto;
			background-color: #A833F5;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			-ms-transform: translate(-50%, -50%);
			-webkit-transform: translate(-50%, -50%);
		}
	</style>
</head>

<body>
	<div class="father">
		<div class="son">利用transform实现横向纵向居中</div>
	</div>
</body>

</html>

//end

猜你喜欢

转载自blog.csdn.net/u013970232/article/details/111385825
今日推荐