css div盒子居中的方法?

本文详细介绍五种常用的网页元素居中布局方法,包括使用margin属性、flex布局、绝对定位、inline-block元素及transform属性,适用于不同场景和元素类型的居中需求。

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

如何让盒子居中?

1、block元素,使用margin属性


.center {
    margin: auto;
    width: 90%;
    border: 3px solid #73AD21;
    padding: 10px;
}
<div class="center">
  <p>我是居中盒子,当width为100%时,margin属性失效。但是盒子还是处于居中状态</p>
</div>

</body>
</html>

2、block元素,在flex容器上使用justify-content:center

注意,不要再元素加fle:1,否则会无法调节div块儿的宽度。以下代码同时可以让div盒子垂直居中

<div class="first">
			<div class="second">
				ddd
			</div>
		</div>

		<style type="text/css">
			.first {
				width: 200px;
				height: 200px;
				background: rgba(255, 255, 0, 0.5);
				display: flex;
				justify-content: center;
				align-items: center;  //配合下方的指定高度样式,可以让div同时垂直居中
			}
			
			.second {
				/*flex: 1;*/
				background: pink;
				height: 50%;
			}
		</style>

3、block 元素,绝对定位、margin-left:-(width/2)和left:50%实现水平居中:

<div class="first">
</div>
		<style type="text/css">
			.first {
				width: 200px;
				height: 50px;
				position: absolute;
				left: 50%;
				margin-left: -100px;
				background: pink;
			}
		</style>

4、inline-block元素,在父级块级元素上使用text-align:center

div{
text-align:center;
}
<div><span>ddd</span></div>

5、任意类型元素。left:50%+tranfrom:translateX(-50%)

<template>
	<div class="box">
		<div class="center">
			
		</div>
	</div>
</template>

<script>
</script>

<style lang="scss" scoped="scoped">
.box{
	width: 90%;
	height: 20%;
	background: red;
	position: relative;
	.center{
		width: 10%;
		height: 100%;
		background: green;
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
	}
}
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值