第19题:让一个div水平垂直居中有几种方式?

170 阅读1分钟

v2-3b6b5c0a611ba4b32115257a63b0c9ad_720w

实现上方效果,下面列举几个常用的方法,个人比较推荐用flex布局实现

方式1(利用margin和绝对定位)

html

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

css

.container {
    position: relative;
    width: 150px;
    height: 150px;
    background-color: #000;

    .box {
        margin: auto;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        width: 50px;
        height: 50px;
        background-color: #fff;
    }
}

方式2(利用flex布局)

html

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

css

.container {
    position: relative;
    width: 150px;
    height: 150px;
    background-color: #000;
    display: flex;
    justify-content: center;
    align-items: center;

    .box {
        width: 50px;
        height: 50px;
        background-color: #fff;
    }
}