CSS属性之position完全理解(实例解析)

本文详细解析了CSS中的position属性,包括它的四种可选值:fixed, absolute, relative, static,以及它们各自的作用。通过实例展示了position属性在布局中的应用,包括如何通过left,right,top,bottom和z-index实现元素的精确定位。


position在css中的作用可谓不一般,当然有时也会让人很dan疼,我想该是时候让她去见上帝了:实例解析

重点内容:

1.position可取的值有:fixed,absolute,relative,static.

2.默认值为static,此时该元素对left,right,top,bottom以及z-index均忽略,即为0;

3.非默认值时,配套left,right,top,bottom以及z-index使用,可达不一般效果;

4.理解实例中的取不同值的意义

<html>
<head>
<title>CSS属性之position完全理解</title>
<style type="text/css">
<!--
body{
	margin:10px;
	font-family:Arial;
	font-size:13px;
	background-color:#555;
}
#father{
	background-color:#a0c8ff;
	border:1px dashed #000000;
	width:500px;
	height:500px;
	position:absolute;
	left:100px;
	top:100px;
	color:gray;
	font-size:20px;
}
#block1{
	background-color:#fff0ac;
	border:1px dashed #000000;
	padding:10px;
	position:absolute;		
	left:50px;				
	top:50px;				
}

#block2{
	background-color:#f990ac;
	border:1px dashed #000000;
	padding:10px;
	position:static; 	/*static为默认值,其默认left,right,top,bottom,z-index等值都均被忽略*/
}
#block21{
	background-color:#f5555c;
	border:1px dashed #000000;
	padding:10px;
	position:absolute;	/*相对于father进行定位,因为其父元素为static,故向上查询继续向上查询到第一个非static父元素.*/
	left:50px;
	top:150px;
	width:100px;
}

#block3{
	background-color:red;
	border:1px dashed #000000;
	padding:10px;
	position:relative;	/*相对于father元素定位*/
	left:30px;
	top:10px;
	width:300px;
}
#block4{
	background-color:green;
	border:1px dashed #000000;
	padding:10px;
	position:fixed;	/*直接相对于body元素定位,其不随页面的滚动而滚动。*/
	left:50px;
	top:120px;
}
-->
</style>
   </head>
<body>
	<div id="father">
		<!--1.当position设置为absolute时:相对于非static的第一个父元素的绝对定位.
		-->
		<div id="block1">absolute--son1</div>
		<div id="block2">
			<div id="block21">absolute--son2-1</div>
		static--son2
		</div>
		<!--2.当position设置为relative时:相对于第一个父元素(直接父元素)的定位.
		-->
		<div id="block3">relative--son3</div>
		
		<!--3.当position设置为fixed时:直接相对于body元素的绝对定位.
		-->
		<div id="block4">fixed-----son4</div>
		absolute---father
	</div>
</body>
</html>


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值