实现css盒子水平垂直的方式

本文介绍了五种使用CSS实现盒子水平垂直居中的方法:通过flex布局、position结合translate、负margin、margin自动分配以及grid布局,并分别详细说明了每种方法的适用场景和代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

水平垂直居中方式

<div class="father">
    <div class="son">温情key</div>
</div>
* {
    margin: 0;
    padding: 0;
}

1. flex

给父元素设置
display: flex;
align-items: center; // 水平居中
justify-content: center; // 垂直居中
已知宽高和未知宽高都可以实现水平垂直居中

.father {
    width: 300px;
    height: 300px;
    background: red;
    display: flex;
    align-items: center;
    justify-content: center;
}

已知宽高

.son {
    width: 100px;
    height: 100px;
    background: aqua;
}

在这里插入图片描述

未知宽高

<div class="father">
        <div class="son">温情key</div>
    </div>
.son {
	background: aqua;
}

在这里插入图片描述

2. position + translate

父元素:position: relative;
子元素:position: absolute;
left: 50%;
top: 50%;
transform: translate(width / 2, height / 2);

.father {
    width: 300px;
    height: 300px;
    background: red;
    position: relative;
}

已知宽高

.son {
	position: absolute;
    width: 100px;
    height: 100px;
    background: aqua;
    top: 50%;
    left: 50%;
    transform: translate(-50px, -50px);  // 也可以用-50%
}

在这里插入图片描述

未知宽高

父元素:position: relative;
子元素:position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);

.father {
    width: 400px;
    height: 300px;
    background: red;
    position: relative;
}

.son {
    background: aqua;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

未知宽高

3. positon + 负margin

已知宽高

父元素设置 position: relative;
子元素: position:absolute;
left: 50%;
top: 50%;
margin-left: - (width / 2);
margin-top: - (height / 2);

.father {
    width: 400px;
    height: 400px;
    background: red;
    position: relative;
}
.son {
    position: absolute;
    background: aqua;
    width: 100px;
    height: 100px;
    left: 50%;
    top: 50%;
    margin-top: -50px;
    margin-left: -50px;
    
}

在这里插入图片描述

4. position + margin: auto

已知宽高

父元素设置 position:relative;
子元素设置 position:absolute;
left: 0;
bottom: 0;
right: 0;
top: 0;
margin: auto;

.father {
    width: 400px;
    height: 400px;
    background: red;
    position: relative;
}

.son {
    position: absolute;
    background: aqua;
    width: 100px;
    height: 100px;
    left: 0;
    bottom: 0;
    right: 0;
    top: 0;
    margin: auto;
}

在这里插入图片描述

5. grid

父元素添加 display:grid;
子元素添加 align-self: center;
justify-self: center;

有无宽高都适用

.father {
    width: 400px;
    height: 400px;
    background: red;
    display: grid;
}

.son {
    background: aqua;
    align-self: center;
    justify-self: center;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温情key

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值