前端面试题:块级元素水平垂直居中的五种常见方法

文章介绍了使用CSS进行块级元素水平垂直居中的五种常见方法,包括:1)grid布局,通过align-self和justify-self属性;2)弹性盒子,利用display:flex和justify-content/align-items属性;3)绝对定位结合负margin;4)绝对定位和marginauto;5)绝对定位配合transform进行过渡调整。

常用的块级元素的水平垂直居中CSS方法(5种)

方法一:grid:网格布局

给父元素设置:display:grid
给子元素设置:align-self:center;  justify-self:center;
	#box{
        background-color: aquamarine;
        width: 500px;
        height: 500px;
        display: grid;
    }
    #boxSon{
        background-color: rgb(211, 184, 49);
        width: 200px;
        height: 200px;
        align-self: center;
        justify-self: center;
    }

方法二: 弹性盒子

只需要给父元素设置:
display:flex;
justify-content:center;
align-items:center;
	#box {
        background-color: aquamarine;
        width: 500px;
        height: 500px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    #boxSon {
        background-color: rgb(211, 184, 49);
        width: 200px;
        height: 200px;
    }

方法三: 绝对定位+负margin

需知道子元素盒子大小:margin=负盒子宽度的一半
	#box {
        background-color: aquamarine;
        width: 500px;
        height: 500px;
        position: relative;
    }
    #boxSon {
        background-color: rgb(211, 184, 49);
        width: 200px;
        height: 200px;
        position: absolute;
        top: 50%;
        left: 50%;
        margin: -100;
    }

方法四: 绝对定位+margin

不需知道子元素盒子大小
	#box {
        background-color: aquamarine;
        width: 500px;
        height: 500px;
        position: relative;
    }
    #boxSon {
        background-color: rgb(211, 184, 49);
        width: 200px;
        height: 200px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
    }

方法五: 绝对定位+过渡

不需要子元素固定宽高
子:top: 50%;
    left: 50%;
    transform:translate(-50%, -50%)
	#box {
        background-color: aquamarine;
        width: 500px;
        height: 500px;
        position: relative;
    }

    #boxSon {
        background-color: rgb(211, 184, 49);
        width: 200px;
        height: 200px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform:translate(-50%,-50%);
    }
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值