CSS中嵌套关系盒子水平垂直居中的方法

1.定位+margin外边距:

父级相对定位,子级绝对定位+左和上外边距为子盒子的一半

.father {
            width: 400px;
            height: 400px;
            background-color: pink;
            margin: 100px auto;
            position: relative;
        }

        .father .son {
            position: absolute;
            margin-left: 100px;
            margin-top: 100px;
            width: 200px;
            height: 200px;
            background-color: plum;
        }

2.定位+transfrom

父级相对定位,子级绝对定位+位移(x,y轴都移动子盒子自身的一半)

.father {
            width: 400px;
            height: 400px;
            background-color: pink;
            margin: 100px auto;
            position: relative;
        }

        .father .son {
            position: absolute;
            transform: translate(100px,100px);
            width: 200px;
            height: 200px;
            background-color: plum;
        }

3.定位+方位名词

父级相对定位,子级绝对定位+位移(x,y轴都移动子盒子自身的一半)
这里移动子盒子自身距离的一半都用50%来表示,实际是对盒子居中方式---定位+transfrom的优化

.father {
            width: 400px;
            height: 400px;
            background-color: pink;
            margin: 100px auto;
            position: relative;
        }

        .father .son {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,50%);
            width: 200px;
            height: 200px;
            background-color: plum;
        }

 4.定位+margin : auto

 .father {

            width: 400px;

            height: 400px;

            border: 1px solid #000;

            position: relative;

        }

        .father .son {

            width: 200px;

            height: 200px;

            border: 1px solid #999;

            position: absolute;

            margin: auto;

            top: 0;

            left: 0;

            right: 0;

            bottom: 0;

        } 

5.flex布局

父级添加flex布局,并且添加x,y轴居中对齐方式 (只用操作父级 不用考虑子级 轻松搞定)

.father {
            width: 400px;
            height: 400px;
            background-color: pink;
            margin: 100px auto;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .father .son {
            width: 200px;
            height: 200px;
            background-color: plum;
        }

6.利用display:table-cell

 .father {

            width: 400px;

            height: 400px;

            border: 1px solid #000;

            display: table-cell;

            vertical-align: middle;

            text-align: center;

        }

        .father .son {

            width: 200px;

            height: 200px;

            border: 1px solid #999;

            display: inline-block;

        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值