css uses position + transform to realize the horizontal and vertical centering of the flexible box

The front end often has the requirement of "centering horizontally and vertically", and it is easy to fix the width and height.
When the width and height are uncertain, I recommend the following method to everyone

The principle is actually two points

  • position: absolute; 100% refer to the parent element
  • Transform: translate(-50%, -50%); 100% refer to the current element

The combined effect of position and transform is to align the parent element with the midpoint of the current element , so as to achieve the centering effect

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

Guess you like

Origin blog.csdn.net/u013970232/article/details/111385825