水平垂直居中的几种方法

前言

最近刷前端面试题经常看到CSS水平垂直居中设置的题目,找了下相关方法试了下,总结了一些比较常用的。
这里统一设置父元素和定位子元素为

<div class="box">
        <div id="content"></div>
</div>
.box{
        width: 400px;
        height: 400px;
        background: #cae;
}
#content {
        width: 300px;height: 300px;
        background: #fc1;
}
(一)position方法

设置父元素相对定位,子元素绝对定位,利用子元素的绝对定位使子元素水平垂直居中,这种方法要知道元素的大小;

.box {
        width: 400px;
        height: 400px;
        background: #cae;
        position: relative;
    }
#content {
        width: 300px;height: 300px;
        background: #fc1;
        position: absolute;
        top: 50px;left: 50px;
    }
(二)position+margin方法

1.父元素相对定位,子元素绝对定位距离都设置为0,利用margin:auto;使子元素水平垂直居中.

.box2 {
        width: 400px;
        height: 400px;
        background: #f1f;
        position: relative;
    }
#content2 {
        width: 300px;height: 300px;
        margin:auto;
        background: #fc1;
        position: absolute;
        top: 0;left:0;bottom: 0;right: 0;
    }

2.1.父元素相对定位,子元素绝对定位距离设置为50%(这里50%应该是父元素大小的50%),通过设置子元素大小的一半的负margin值使子元素水平垂直居中.

.box3{
        width: 400px;
        height: 400px;
        background: #23f;
        position: relative;
    }
#content3 {
        width: 300px;height: 300px;
        background: #fc1;
        position: absolute;
        top: 50%;left: 50%;
        margin-top: -150px;
        margin-left: -150px;
    }
(三)table-cell 方法
.box4{
        width: 400px;
        height: 400px;
        background: #456;
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }
#content4 {
        width: 300px;height: 300px;
        background: #fc1;
        display: inline-block;
    }
(四)position+transform 方法
.box5{
        width: 400px;
        height: 400px;
        background: #789;
        position: relative;
    }
#content5 {
        width: 300px;height: 300px;
        margin:auto;
        background: #fc1;
        position: absolute;
        top: 50%;left: 50%;
        -webkit-transform:translate(-50%,-50%);
        transform:translate(-50%,-50%);
    }
(五)flex 方法

1.利用弹性布局flex:设置align-items,justify-content都为center;

.box6{
        width: 400px;
        height: 400px;
        background: #1f1;
        display: flex;
        align-items:center;
        justify-content:center;
    }
#content6 {
        width: 300px;height: 300px;
        background: #fc1;
    }

2.弹性布局,子元素margin设置auto即可.

.box7{
        width: 400px;
        height: 400px;
        background: #aaf;
        display: flex;
    }
#content7 {
        width: 300px;height: 300px;
        background: #fc1;
        margin:auto;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值