【前端】几种实现水平垂直居中的方法总结

本文介绍了六种实现网页元素垂直居中的方法,包括使用绝对定位、相对定位、line-height、Flex布局等技术手段,为前端开发者提供了实用的布局解决方案。

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

实现代码:

<!DOCTYPE html>
<html>
<head>
	<title>垂直居中</title>
	<meta charset="utf-8">
	<script type="text/javascript"></script>
	<style type="text/css">
		/* 方法 1  子元素 position:absolute 0 0 0 0*/
		#container1{
			width: 400px;
			height: 400px;
			position: relative;
			background-color: #f5f5f5;
		}
		#item1{
			width: 200px;
			height: 200px;
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			margin: auto;
			background-color: #03c03c;
		}
		
		/* 方法 2  子元素 position:absolute*/
		#container2{
			margin-top: 20px;
			width: 400px;
			height: 400px;
			position: relative;
			background-color: #f5f5f5;
		}
		#item2{
			width: 200px;
			height: 200px;
			position: absolute;
			left: 50%;
			margin-left: -100px;
			top: 50%;
			margin-top: -100px;
			background-color: #03c03c;
		}
		
		/* 方法 3 子元素 position:relative*/
		#container3{
			position: relative;
			margin-top: 20px;
			width: 400px;
			height: 400px;
			background-color: #f5f5f5;
		}
		#item3{
			width: 200px;
			height: 200px;
			position: relative;
			left: 50%;
			margin-left: -100px;
			top: 50%;
			margin-top: -100px;
			background-color: #03c03c;
		}
		
		/* 方法 4 line-height*/
		#container4{
			width: 400px;
			height: 400px;
			line-height: 100px;
			background-color: #f5f5f5;
			margin-top: 20px;
		}
		#item4{
			width: 200px;
			height: 200px;
			margin: 0 auto;
			background-color: #03c03c;
		}
		
		/* 方法 5  display:flex*/
		#container5{
			width: 400px;
			height: 400px;
			display: flex;
			align-items: center;
			justify-content: center;
			background-color: #f5f5f5;
			margin-top: 20px;
		}
		#item5{
			width: 200px;
			height: 200px;
			background-color: #03c03c;

		}
		
		/* 方法 6  display:box; */
		#container6{
			height: 400px;
			width: 400px;
			margin-top: 20px;
			background-color: #f5f5f5;
			display: -webkit-box;
			display: box;
			-webkit-box-align: center;
			-webkit-box-pack: center;
			box-align: center;
			box-pack: center;
		}
		#item6{
			height: 200px;
			width: 200px;
			background-color: #03c03c;
		}
	</style>
</head>
<body>
<div id="container1">CONTAINER1
	<div id="item1">ITEM1</div>
</div>

<div id="container2">CONTAINER2
	<div id="item2">ITEM2</div>
</div>

<div id="container3">CONTAINER3
	<div id="item3">ITEM3</div>
</div>

<div id="container4">CONTAINER4
	<div id="item4">ITEM4</div>
</div>

<div id="container5">
	<div id="item5"></div>
</div>

<div id="container6">
	<div id="item6"></div>
</div>
</body>
</html>

  

 

转载于:https://www.cnblogs.com/dragonir/p/7686257.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值