CSS中水平垂直居中的几种常用方法

本文详细介绍了CSS中实现元素水平垂直居中的四种常见方法:1) 使用flex布局,设置justify-content和align-items为center;2) 通过绝对定位,设置top, bottom, left, right为0,并使用margin: auto;3) 结合绝对定位和transform,调整元素位置使其居中;4) 利用行内块元素和伪元素实现居中。这些方法在不同场景下各有优势,开发者可根据需求选择合适的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果:

    <div class="outer">
        <div class="inner">oooo.oooo</div>
    </div>

1、flex弹性布局

        外层容器设置flex弹性布局,设置主轴和交叉轴center

    <style>
        .outer{
            width: 200px;
            height: 200px;
            background-color: skyblue;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .inner{
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>

2、绝对定位 + 相对定位 + margin

        设置需要内层元素绝对定位,上下左右为0,margin:auto

    <style>
        .outer{
            width: 200px;
            height: 200px;
            background-color: skyblue;
            position: relative;
        }
        .inner{
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
        }
    </style>

3、绝对定位 + 相对定位 + margin / transform

        使用margin、transform其中一种即可

     <style>
        .outer{
            width: 200px;
            height: 200px;
            background-color: skyblue;
            position: relative;
        }
        .inner{
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;
            top: 50%;
            left: 50%;
            /* 方式1:利用margin回移自身宽高的50% */
            margin-top: -50px;
            margin-left: -50px;
            /* 方式2:利用translate回移 */
            transform: translate(-50%,-50%);
        }
    </style>

4、设置为行内块 + text-align: center +  vertical-align: middle

        需要添加伪元素,并设置高度100%,然后利用行内元素居中的方式设置水平垂直居中

    <style>
        .outer{
            width: 200px;
            height: 200px;
            background-color: skyblue;
            text-align: center;
        }
        .outer::after{
            display: inline-block;
            content: '';
            width: 0;
            height: 100%;
            vertical-align: middle;
        }
        .inner{
            background-color: pink;
            display: inline-block;
            vertical-align: middle;
        }
    </style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值