div垂直水平居中

2020-10-26  本文已影响0人  麦西的西
盒子垂直水平居中.jpg
<div class="box">
    <div class="inner-box"></div>
</div>

面试总经常会问到盒子垂直水平居中的问题,整理了一下常用的方法:

1. 使用absolute + transform

.box {
    position: relative;
    width: 500px;
    height: 500px;
    border: 1px solid pink;
}
.inner-box {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 200px;
    height: 200px;
    transform: translate(-50%, -50%);
    border: 1px solid skyblue;
}

2. 使用absolute + margin(margin: auto)

.box {
    position: relative;
    width: 500px;
    height: 500px;
    border: 1px solid pink;
}
.inner-box {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    width: 200px;
    height: 200px;
    border: 1px solid skyblue;
}

3. flex布局

.box {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 500px;
    height: 500px;
    border: 1px solid pink;
}
.inner-box {
    width: 200px;
    height: 200px;
    border: 1px solid skyblue;
}

4. 知道内部盒子大小的话,可以使用absolute + margin(margin-top, margin-left为负值)

.box {
    position: relative;
    width: 500px;
    height: 500px;
    border: 1px solid pink;
}
.inner-box {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -100px;
    margin-left: -100px;
    width: 200px;
    height: 200px;
    border: 1px solid skyblue;
}

5. 知道内部盒子大小的话,还可以使用calc来计算margin

.box {
    width: 500px;
    height: 500px;
    border: 1px solid pink;
}
.inner-box {
    margin-top: calc((100% - 200px)/2);
    margin-left: calc((100% - 200px)/2);
    width: 200px;
    height: 200px;
    border: 1px solid skyblue;
}
上一篇 下一篇

猜你喜欢

热点阅读