使用position定位元素

div定位中position的使用说明:

共四个选项:static、absolute、relative和fixed。其中absolute和relative最为常用。

使用absolute定位:

position:absolute;表示字块已经不再属于父块了,字块左边框的位置是相对于页面<body>左边的边距,字块上边框是相对于<body>上边框的位置。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#div1{width:300px;height:80px;border:1px solid blue;margin-top:20px;margin-left:30px;}
			.div2{width:170px;height:30px;border:1px solid blue;background-color: yellow;
			position:absolute;top:40px;left:60px;}
		</style>
	</head>
	<body>
		<div id="div1">
			<div class="div2">div绝对定位</div>
		</div>
	</body>
</html>

使用relative定位:当position:relative时,与absolute完全不同,这时字块是相对于其父块来进行定位的需要设置top和left两个值。提示:top或left的值除了px之外还可以设置成百分比。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#div1{width:300px;height:80px;border:1px solid blue;margin-top:20px;margin-left:30px;}
			.div2{width:170px;height:30px;border:1px solid blue;background-color: yellow;
			position:relative;top:80px;left:60px;}
		</style>
	</head>
	<body>
		<div id="div1">
			<div class="div2">div绝对定位</div>
		</div>
	</body>
</html>

空间位置z-index该属性用于调整定位时重叠块的上下位置

z-index的值大的页面位于其值小的的上方(离我们越近值越大)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			#div1{width:300px;height:80px;border:1px solid blue;margin-top:20px;margin-left:30px;z-index: 20;}
			.div2{width:170px;height:30px;border:1px solid blue;background-color: yellow;
			position:absolute;top:80px;left:60px;z-index: 1;}
			.div3{width:180px;height:40px;border:1px solid blue;background-color: yellow;
			position:absolute;top:90px;left:70px;z-index:4;}
		</style>
	</head>
	<body>
		<div id="div1">
			<div class="div2">div绝对定位</div>
			<div class="div3">块2</div>
		</div>
		
	</body>
</html>

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值