实现垂直居中的几种方式

  • 使用绝对定位加负外边距,具体的代码为
<div class="box">
   		<div class="child">
   		</div>
</div>

.box {
   			width: 300px;
   			height: 300px;
   			background: lightblue;
   			position: relative;
   		}
   		
   		.child {
   			width: 100px;
   			/*				这里的width和height可以使用百分比,那么margin也应该设置为百分比,并且满足为自身高度的一半*/
   			height: 100px;
   			position: absolute;
   			background: lightcoral;
   			margin: -50px 0 0 0;
   			/*margin为自身高度的一半*/
   			top: 50%;
   		}

这种方式的兼容性比较高,可以不用知道父元素的宽高,但是需要知道被居中元素的高度,因为margin需要设置为自身高度的一半

  • 使用绝对定位加transform,具体的代码如下
<div class="box1">
   		<div class="child1"></div>
   	</div>
.box1 {
   			width: 300px;
   			height: 300px;
   			background: lightblue;
   			position: relative;
   		}
   		
   		.child1 {
   			background: orange;
   			position: absolute;
   			top: 50%;
   			transform: translate(0, -50%);
   			width: 200px;
   			height: 200px;
   		}

这种方式的好处是既不用知道父元素的尺寸,也不用知道被居中元素的尺寸,因为transform中的translate偏移的百分比就是相对于元素本身的尺寸而言的

  • 使用padding
<div class="box2">
   	 	<div class="child2">
   	 		
   	 	</div>
   	</div>
.box2 {
   			width: 300px;
   			background: lightblue;
   			padding: 100px 0;
   		}
   		
   		.child2 {
   			width: 200px;
   			height: 200px;
   			background: orange;
   		}

这种办法需要知道父元素和子元素的宽高,因为这种方法的实现方式是父元素的高=内上边距+子元素的高+内下边距的高

  • 使用flex布局(align-items)
<div class="box3">
   		<div class="child3"></div>
</div>
   	
.box3 {
   			width: 300px;
   			height: 300px;
   			background: lightblue;
   			display: flex;
   			align-items: center;
   		}
   		
   		.child3 {
   			width: 100px;
   			height: 100px;
   			background: orange;
   		}
  • 使用flex布局(flex-direction+justify-content)
<div class="box4">
   		<div class="child4"></div>
</div>

.box4 {
   			width: 300px;
   			height: 300px;
   			background: lightblue;
   			display: flex;
   			flex-direction: column;
   			justify-content: center;
   		}
   		
   		.child4 {
   			width: 300px;
   			height: 100px;
   			background: orange;
   		}
  • 让文字垂直居中
<div class="box5">
   		<div class="child5">vertial align</div>
</div>

.box5{
   			width: 300px;
   			height: 300px;
   			background: lightblue;
   			display:table;
   		}
   		
   		.child5{
   			display:table-cell;
   			vertical-align: middle;
   			background: orange;
   		}

猜你喜欢

转载自blog.csdn.net/weixin_42424269/article/details/88852877