css实现垂直水平居中

方案一
div决定定位垂直水平居中(margin:auto实现绝对定位元素的居中)
兼容性:IE7以及之前版本不支持

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>垂直水平居中</title>
		<style type="text/css">
			#content {
				width: 200px;
				height: 200px;
				background: lightblue;
				position: absolute;
				left: 0;
				top: 0;
				bottom: 0;
				right:0;
				margin: auto;
			}
		</style>
	</head>
	<body>
		<div id="content"></div>
	</body>
</html>

方案二
div绝对定位垂直水平居中(margin负间距)这或许是当前最流行的使用方法。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>垂直水平居中</title>
		<style type="text/css">
			#content {
				width: 200px;
				height: 200px;
				background: lightblue;
				position: absolute;
				left:50%;
				top: 50%;
				margin-left: -100px;
				margin-top: -100px;
			}
		</style>
	</head>
	<body>
		<div id="content"></div>
	</body>
</html>

方案三:
div绝对定位垂直水平居中(Transforms变形)
兼容性:IE8不支持;

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>垂直水平居中</title>
		<style type="text/css">
			#content {
				width: 200px;
				height: 200px;
				background: lightblue;
				position: absolute;
				left:50%;
				top: 50%;
				transform: translate(-50%,-50%);
			}
		</style>
	</head>
	<body>
		<div id="content"></div>
	</body>
</html>

方案四:
使用flex
css高垂直水平居中(相对于父级元素

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>垂直水平居中</title>
		<style type="text/css">
			.box {
				height: 600px;
				border: 2px solid black;
				display: flex;
				justify-content: center;
				align-items: center;
			}
			
			#content {
				background: lightblue;
				width: 100px;
				height: 100px;
			}
		</style>
	</head>
	<body>
		<div class="box">
			<div id="content"></div>
		</div>
	</body>
</html>

方案五:
使用flex
使div在整个页面垂直水平居中

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>垂直水平居中</title>
		<style type="text/css">
			html,body {
				height: 100%;
			}
			
			body {
				display: flex;
				align-items: center;
				justify-content: center;
			}
			
			#content {
				background: lightblue;
				margin: 0 auto;
			}
		</style>
	</head>
	<body>
			<div id="content">垂直水平居中</div>
	</body>
</html>

方案六:
使用display:table-cell
css高垂直水平居中(相对于父级元素

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>垂直水平居中</title>
		<style type="text/css">
			.box {
				width: 300px;
				height: 300px;
				border: 2px solid black;
				display: table-cell;
				text-align: center;
				vertical-align: middle;
			}
			#content {
				width: 100px;
				height: 100px;
				background: lightblue;
				display: inline-block;
			}
		</style>
	</head>
	<body>
		<div class="box">
			<div id="content">垂直水平居中</div>
		</div>
	</body>
</html>

总结:css的布局还是需要多多练习,今天做笔试时突然发现自己在这一块有些遗忘了,所以整理了这六种跟可以让div垂直居中的方法,分别是绝对布局和flex,table-cell演变出来的,如果还有其他更好的方法还望大家多多交流~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值