如何实现垂直水平居中?

如何实现垂直水平居中?

第一种 position定位+margin负距离

前提是知道居中元素的宽高,首先给居中元素定位,之后设置margin的负距离为具体宽高的一半便可达到垂直居中效果

 .box {
        width: 500px;
        height: 500px;
        background: pink;
        position: relative;
        border: 10px solid red;
    }

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

第二种 position定位+margin auto

position定位加margin auto,与第一种方法相似,设置居中元素的top bottom left right为0px,之后加上外边距magin auto即可

.box {
        width: 500px;
        height: 500px;
        background: pink;
        position: relative;
        border: 10px solid red;
    }

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

第三种 position+transform

position定位加上transfom 这种方式的特点是可以不用知道居中元素的宽高,给居中元素定位后left和top都设置成50%,之后向反向平移50%即可

.box {
        width: 500px;
        height: 500px;
        background: pink;
        position: relative;
        border: 10px solid red;
    }

    .box-child {
        background-color: green;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }

第四种flex布局

首先给父元素设置display:flex让其变成弹性盒子,然后利用弹性盒子的jusyify-content和align-items,将两个属性都设置为center即可
注意:不是给子元素设置 是给容器父元素设置
 .box {
        width: 500px;
        height: 500px;
        background: pink;
        border: 10px solid red;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .box-child {
        width: 200px;
        height: 200px;
        background-color: green;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值