推荐三种超好用的div绝对居中的方法

本文介绍三种实现div水平垂直居中的方法:利用CSS3的transform属性、使用display:inline-block结合特定行高,以及通过JavaScript动态调整位置。这些方法简单实用,适用于不同场景。

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

在实际开发过程中我们经常会遇到div水平、垂直方向绝对居中的布局需求,在开发过程中div布局通过计算宽和高来用margin、padding定位的方式来达到要求,太过繁琐,有时候还因为布局需求,不能给出定高和宽,而达不到要求,今天给大家推荐三种超好用的方法。
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			.first>.fa{position:relative ;}
			.first>.fa>.son{position:absolute ;left: 50%;top: 50%;transform: translate(-50%,-50%);}
			.second>.fa{position:relative ;text-align: center;line-height:225px;}/*行高设置时需要加上子元素高度的一半*/
			.second>.fa>.son{display: inline-block;}
			.third>.fa{position:relative ;}
			.third>.fa>.son{position: absolute;}
		</style>
		
	</head>
	<body>
		<p>方法一:css3 手段</p>
		<div class="first">
			<div class="fa" style="width:200px;height:200px;background:red;">
				<div class="son" style="width:50px;height:50px;background: yellow;">
				
				</div>
			</div>
		</div>
		<p>方法二:display: inline-block;</p>
		<div class="second">
			<div class="fa" style="width:200px;height:200px;background:red;">
				<div class="son" style="width:50px;height:50px;background: yellow;">					
				</div>
			</div>
		</div>
		<p>方法三:js手段</p>
		<div class="third">
			<div id="fu" class="fa" style="width:200px;height:200px;background:red;">
				<div id="zi" class="son" style="width:50px;height:50px;background: yellow;">					
				</div>
			</div>
		</div>
	</body>
	<script>
			
		var fu = document.getElementById("fu");
		var zi = document.getElementById("zi");	
		zi.style.left=(fu.offsetWidth-zi.offsetWidth)/2+"px";
		zi.style.top=(fu.offsetHeight-zi.offsetHeight)/2+"px";
	</script>
</html>


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值