CSS使元素水平垂直居中的方法

1、使用绝对定位(position)和外边距(margin)

      方法:(1)将父级 (box)设置成相对定位(relative);(2)将子级(content)设置成绝对定位(absolute);(3)将子级(content)top、left设置成50%;(4)将子级(content)margin-left设置成 -(子级宽度的一半);(5)将子(content)margin-top设置成 -(子级高度的一半)

<!DOCTYPE html>
<html>
<head>
	<title>元素居中方法一</title>
	<style type="text/css">
		*{
			padding: 0;
			margin: 0;
		}
		.box{
			width:400px;
			height: 300px;
			background: green;
			position: relative;
		}
		.content{
			width: 100px;
			height: 80px;
			background: blue;
			position: absolute;
			left: 50%;
			top:50%;
			margin-left: -50px;
			margin-top:-40px;
		}
	</style>
</head>
<body>
<div class="box">
	<div class="content"></div>
</div>
</body>
</html>

2、使用绝对定位(absolute)和外边距(margin:auto)

方法:(1)将父级(box)设置成相对定位(relative);(2)将子级(content)设置成绝对定位(absolute);(3)将子级(content)的top、right、bottom、left设置成0;(4)将子级(content)的margin设置成auto;

<!DOCTYPE html>
<html>
<head>
	<title>方法二</title>
	<style type="text/css">
		.box{
			width: 400px;
			height: 300px;
			position: relative;
			background: blue;
		}
		.content{
			width: 200px;
			height: 100px;
			position: absolute;
			margin: auto;
			left: 0;
			right: 0;
			top:0;
			bottom:0;
			background: green;
		}
	</style>
</head>
<body>
	<div class="box">
		<div class="content"></div>
	</div>
</body>
</html>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值