CSS水平垂直居中的几种实现方式

1.利用 position:absolute

<div class="father">
     <div class="son"></div>
</div>
  1. 当已知元素宽度和高度时,可以设置position: absolute和margin为负的宽高的一半
<style>
    .father{
          
   
        position: relative;
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
          
   
        position: absolute;
        background-color: red;
        width:50px;
        height: 50px;
        left: 50%;
        top: 50%;
        margin-top: -25px;
        margin-left: -25px;
    }
</style>
  1. 当元素宽度和高度未知时,可以设置position: absolute和transform: translate(-50%, -50%)
.father{
          
   
        position: relative;
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
          
   
        position: absolute;
        width: 50px;
        height: 50px;
        background-color: red;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }

2. 利用margin:auto

.father{
          
   
        position: relative;
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
          
   
        position: absolute;
        background-color: red;
        width: 50px;
        height: 50px;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }

3. 利用弹性盒子

通过给父元素设置display:flex来实现居中

.father{
          
   
        display: flex;
        justify-content: center; //主轴
        align-items: center; //侧轴
        background-color: pink;
        width: 200px;
        height: 200px;
    }
    .son{
          
   
        background-color: red;
        width: 50px;
        height: 50px;
    }

4. 利用水平对齐和行高

设置text-align:center和line-height:height实现单行文本水平垂直居中

<div class="father">
     <div class="son">我要居中</div>
</div>
.father{
          
   
	        background-color: pink;
	        width: 200px;
	        height: 200px;
	        text-align: center;
	}
	.son{
          
   
	    line-height: 200px;
	}
经验分享 程序员 微信小程序 职场和发展