前端面试中最常问到的垂直水平居中问题

方法一、 CSS3 transform和position(元素宽高未知的情况)

<div class="box">
    <span>宽高未知</span>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    position:relative;
}
.box span {
    background: red;
    position: absolute;
    left: 50%;
    top: 50%;
    color: #fff;
    transform: translate(-50%, -50%);
}

方法二、 绝对定位和margin-left:-自身宽度一半,margin-top: -自身高度的一半 (已知宽高)

<div class="box">
    <span>宽高已知</span>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    position: relative;
}
.box span {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: red;
    text-align: center;
    line-height: 100px;
    position: absolute;
    left: 50%;
    top: 50%;
    color: #fff;
    margin-left: -50px;
    margin-top: -50px;
}

方法三、 css3 flex布局

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

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    display:flex;
    justify-content:center;
    align-items: center;
}
.box .child {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: red;
}

方法四、 被居中的元素是inline或者inline-block元素

<div class="box">
    <span class="child">inline和inline-block元素</span>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.box .child {
    display: inline-block;
    width: 100px;
    height: 100px;
    background: red;
}

方法五、绝对定位和margin:auto

<div class="box">
    <div class="child">定高</div>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    position: relative;
}
.box .child {
    width: 100px;
    height: 100px;
    background: red;
    text-align: center;
    color: #fff;
    line-height: 100px;
    position: absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    margin: auto;
}

方法六、line-height: 父级高度和text-align: center

<div class="box">
    <span class="child">line-height</span>
</div>

.box {
    width: 400px;
    height: 400px;
    background: #ccc;
    line-height: 400px;
    text-align: center;
    font-size: 0;
}
.box .child {
    background: red;
    font-size: 14px;
    color: #fff;
}

猜你喜欢

转载自www.cnblogs.com/baimeishaoxia/p/11834690.html