css中常用的几种水平垂直居中方案

文章详细介绍了使用CSS将盒子居中显示的六种常见技术,包括通过margin挤压、设置padding和边框盒子、子绝父相的定位方式,以及使用flex布局。这些方法可以实现水平居中,甚至垂直居中。

1.给父盒子设置border 通过margin挤压

例如先给两个盒子设定父子关系

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

然后给父盒子设置border等属性

.parent {
        width: 200px;
        height: 200px;
        background-color: blue;
        border: 1px solid red;
}

然后给子盒子设置margin属性

.child {
        width: 100px;
        height: 100px;
        background-color: red;
        margin: 50px;
    }

盒子就可以水平居中了

2.通过给父盒子设置padding挤压 ,给父盒子设置为边框盒子

给父盒子设置padding属性,并设置边框盒子

.parent {
        width: 200px;
        height: 200px;
        background-color: blue;
        padding: 50px;
        box-sizing: border-box;
}

子盒子设置宽高背景色等基本属性

.child {
        width: 100px;
        height: 100px;
        background-color: red;
}

这种方法也可以让盒子水平居中

3.(子绝父相)

  给父盒子设置相对定位

position: relative;

  给子盒子设置绝对定位 配合属性都为0

.child {
        width: 100px;
        height: 100px;
        background-color: red;
         position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto; 
    }

4.(子绝父相)

给子盒子设置配合属性 top 50% ,left 50% ,margin-left:-width/2  ,margin-top:-height/2

先给父盒子设置相对定位

position: relative;

然后给子盒子设置绝对定位,也可使子盒子水平垂直居中于父盒子中

.child {
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-left: -50px;
        margin-top: -50px; 
    }

5.给父盒子设置display:flex justify-content:center align-items:center

先给父盒子设置

.parent {
        width: 200px;
        height: 200px;
        background-color: red;
        margin: 0 auto;
        display: flex;
        justify-content: center; 
        align-items: center; 

    }

然后是子盒子

.child {
        width: 100px;
        height: 100px;
        background-color: blue;
    }

效果如图所示:

6.给父盒子设置display:flex 给子盒子设置margin:auto

给父盒子设置display: flex

.parent {
        width: 200px;
        height: 200px;
        background-color: red;
        margin: 0 auto;
        display: flex; 
    }

然后给子盒子设置

.child {
        width: 100px;
        height: 100px;
        background-color: blue;
        margin: auto; 
    }

以上就是css中常用的让盒子水平居中的方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值