CSS 未知宽高水平垂直居中方案总结

161 阅读1分钟
  1. 方法一

父元素设置为 flex 布局,并设置 justify-content:centeralign-items:center ,令其主轴和交叉轴的对齐方式为居中

<div class="fu">
    <div class="son">
        子元素
    </div>
</div>
.fu {
        height: 500px;
        width: 500px;
        background-color: burlywood;
        display: flex;
        justify-content: center;
        align-items: center;
 }
    .son {
        height: 100px;
        width: 100px;
        background-color: red;
}
  1. 方法二

父元素设置为 flex 布局,子元素的 margin 设置为 auto

<div class="fu">
    <div class="son">
        子元素
    </div>
</div>
.fu {
        height: 500px;
        width: 500px;
        background-color: burlywood;
        display: flex;
 }
    .son {
        height: 100px;
        width: 100px;
        background-color: red;
        margin:auto;
}
  1. 方法三

父元素设置为绝对定位, position:relative ,子元素设置为绝对定位,position: absolute;设置距离 top:50% ,左边 left:50% ,设置transform:translate(-50%,-50%)

<div class="fu">
    <div class="son">
        子元素
    </div>
</div>
.fu {
        height: 500px;
        width: 500px;
        background-color: burlywood;
        position: relative;
 }
.son {
        height: 100px;
        width: 100px;
        background-color: red;
         position: absolute;
        top:50%;
        left: 50%;
        transform: translate(-50%,-50%);
}