实现盒子水平垂直居中的方法

本文详细介绍了使用CSS实现盒子在父容器中水平垂直居中的四种方法,包括利用绝对定位配合margin、利用绝对定位结合transform、简洁的margin auto方法以及现代的flex布局方案,适合初学者及需要快速回顾的前端开发者。

实现盒子水平垂直居中的方法

以下仅限个人的经验所得,希望对你有所帮助
.f 为父盒子 .s 为子盒子

方法一:当盒子可以设置固定宽高的时候,

.f {
width: 500px;
height: 500px;
background-color: #000;
position: relative;

}
.s  {
    width: 100px;
    height: 100px;
    background-color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -50px;
    margin-top: -50px;
    
}

方法二: 一种简洁直观的方法

.f {
width: 500px;
height: 500px;
background-color: #000;
position: relative;

}
.s  {
    width: 100px;
    height: 100px;
    background-color: #fff;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0; 
    right: 0;
    margin :auto;
}

方法三 位移


.f {
width: 500px;
height: 500px;
background-color: #000;
position: relative;

}
.s  {
    width: 100px;
    height: 100px;
    background-color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

方法四 flex布局


.f {
width: 500px;
height: 500px;
background-color: #000;
display :flex;
justify-content :center;
align-items :center;
}
.s {
width: 100px;
height: 100px;
background-color: #fff;
}

加油!
在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值