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

本文详细介绍六种使用CSS实现元素水平垂直居中的方法:利用transform和position、绝对定位配合margin、flex布局、table-cell布局、绝对定位加margin:auto及line-height结合text-align。每种方法适用于不同场景,如元素宽高未知、已知或特定布局需求。

方法一、 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值