div盒子垂直水平居中的几种常见方式(七种)

6 篇文章 0 订阅
6 篇文章 0 订阅

七种简单又好记的css样式使div盒子水平垂直居中!!!

html样式

<div class="big">
        <div class="small"></div>
</div>

第一种:使用margin

        .small{
            width: 200px;
            height: 200px;
            background-color: pink;
            margin: 0 auto;
        }

第二种:使用flex

        .big{
           display: flex;
           justify-content:center;
           align-items: center;
           background-color:red;
        }
        .small{
            width: 200px;
            height: 200px;
            background-color: pink;
        }

第三种:使用flex加margin

        .big {
            display: flex;
            background-color:red;
        }

        .small {
            width: 200px;
            height: 200px;
            background-color: pink;
            margin:auto;
        }

第四种:使用定位+margin 1

        .big {
            position: relative;
            height: 300px;
            background-color: red;
        }

        .small {
            width: 200px;
            height: 200px;
            background-color: pink;
            position: absolute;

            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }

第五种:使用定位+margin  2  ,但是要知道外面盒子的宽高

        .big {
            position: relative;
            height: 300px;
            width: 300px;
            background-color:red;
        }

        .small {
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;

            left: 50%;
            top: 50%;
            margin-left: -50px;
            margin-top: -50px;
        }

第六种:使用定位+  transform

        .big {
            position: relative;
            height: 300px;
            background-color:red;

        }

        .small {
            width: 200px;
            height: 200px;
            background-color: pink;
            position: absolute;

            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

第七种:line-height + display: inline-block

        .big {

            height: 300px;
            line-height: 300px;
            text-align: center;

        }

        .small {
            display: inline-block;
            background: pink;
            width: 200px;
            height: 200px;
        }

结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值