如何实现垂直居中?

116 阅读1分钟

方法一: position + margin

<div class="son">aaa</div>
.son {
    width100px;
    height:100px;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto 0;
}

方法二: position + margin-top

<div class="son">aaa</div>
.son {
    /*前提是有高度*/
    height: 100px;
    position: absolute;
    top: 50%;
    margin-top: -50px;
}

方法三: position + transform

 <div class="son">aaa</div>
.son {
    width: 100px;
    height: 100px;
    position: absolute; /*脱离文档流*/
    top: 50%; /*偏移*/
    transform: translateY(-50%);
}

方法四: 使用flex布局

<div class="father">
  <div class="son">aa</div>
</div>
.father {
    width: 300px;
    height: 300px;
    background-color: pink;
    display: flex;
    align-items: center;
    /*justify-content: center;*/
 }
.son {
    width: 100px;
    height: 100px;
    background: orange;
}