【CSS】垂直居中的方案

120 阅读1分钟

参考原文:

 <div class="box">
   box
 </div>

1. 已知宽高

  • 父元素设置高度+相对定位:
  • 子元素绝对定位:
  • 子元素top、left: 50%
  • 子元素margin-left、margin-top:自身长度的一半
body,
html {
	// 1.父元素设置高度+相对定位:
	position: relative;
	height: 100%;
}

/* 子元素(已知宽高) */
.box {
	background-color: #bfa;
	/* 已知宽高 */
	width: 300px;
	height: 200px;
	// 2.子元素绝对定位:
	position: absolute;
	// 3.子元素top、left: 50%
	top: 50%;
	left: 50%;
	// 4.子元素margin-left、margin-top:自身长度的一半
	margin-left: -150px;
	margin-top: -100px;
}

2. 未知宽高:flex布局

原理:父元素设置高度+flex布局

html,
body {
	height: 100%;
	display: flex;
	justify-content: center; // 沿着X轴水平居中
	align-items: center; // 沿着y轴水平居中
}

.box {
	background-color: #bfa;
	// width: 300px;
       // height: 200px;
}

3. 未知宽高:transform:translate(-50%, -50%);

html,
body {
	position: relative;
	height: 100%;
}

​ .box {
	background-color: #bfa;
	//  width: 300px;
	//  height: 200px; 

	position: absolute;
	top: 50%;
	left: 50%;
	// 根据真实高度居中
	transform: translate(-50%, -50%);
}