元素垂直、水平居中

本文介绍了在CSS中实现元素垂直水平居中的三种常见方法:子绝父相配合margin调整、弹性盒子布局以及使用absolute定位配以margin: auto。详细解析了每种方法的实现原理和代码示例,帮助开发者更好地掌握网页布局技巧。

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

让一个元素垂直水平居中
// dom结构
<div class='box'>
	<div class='small_box'></div>
</div>

方法一: 子绝父相,top:50%,left:50%,子需要移动本身宽度和高度的一般
.box {
	width: 400px;
	height: 400px;
	background: red;
	position: relative;
}
.small_box {
	width: 200px;
	height: 200px;
	background: yellow;
	// 子元素绝对定位,top 50% left 50%之后是中间的小盒子的最左边居中了
	position: absolute;
	left: 50%;
	top: 50%;
	// 可以使用向左向上移动本身宽度和高度的一半(下面的两行)
	// 也可以使用transform:translate(-50%,-50%)
	margin-left: -100px;
	margin-top: -100px;
}

方法二 :父元素设置成弹性盒子,子元素横向居中,纵向居中
.box {
	width: 400px;
	height: 400px;
	background: red;
	display: flex;
	align-items: center;
	justify-content: center;
}
.small_box {
	width: 200px;
	height: 200px;
	background: yellow;  
}

方法三 :子绝父相,子元素所有定位为0,margin设置auto自适应
.box {
	width: 400px;
	height: 400px;
	background: red;
	position: relative;
}
.small_box {
	width: 200px;
	height: 200px;
	background: yellow;
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	botttom: 0;
	margin: auto;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值