css中position的四个常用属性

本文深入解析了CSS中的四种基本定位方式:relative、absolute、static和fixed的特性与使用场景。通过实例代码展示了每种定位方式如何影响元素的位置,并解释了它们之间的区别。

positon的四个常用基本属性详解:

1、relative:相对定位。相对于其当前所在位置进行定位,比如“left:20”会向元素的leift位置添加20像素。

2、absolute:绝对定位。生成绝对定位的元素,相对于static定位以外的第一个父元素进行定位。元素的位置可以通过left、right、top、bottom来定义。

3、static:静态定位。默认值,没有定位,元素出现在正常流中(忽略top、bottom、left、right或z-index的声明)。

4、fixed:生成固定定位的元素,相对于浏览器窗口进行定位,位置不会随网页进行改变。元素的位置通过left、top、right、bottom属性进行定位。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<style>
		.one{
			background-color: red;
			border: 1px solid gray;
			width: 300px;
			height: 300px;
			float: left;
			position:relative;
			margin: 150px 150px;
		}
		.one_11{
			background-color: blue;
			border: 1px solid gray;
			width: 150px;
			height: 150px;
			/*float: left;*/
			left: 70px;
			top: 70px;
			position: absolute;
		}
		.one_12{
			background-color: gold;
			border: 1px solid gray;
			width: 100px;
			height: 100px;
			/*float: left;*/
			left: 50px;
			top: 50px;
			position: absolute;
		}
		.one_13{
			background-color: orange;
			border: 1px solid gray;
			width: 80px;
			height: 80px;
			/*float: left;*/
			top: 80px;
			position: absolute;
		}
		.one_14{
			background-color: purple;
			border: 1px solid gray;
			width: 80px;
			height: 80px;
			/*float: left;*/
			position: absolute;
		}
		.one1{
			background-color: green;
			border: 1px solid gray;
			width: 100px;
			height: 100px;
			/*float: left;*/
			position: absolute;
		}
		.one2{
			background-color: pink;
			border: 1px solid gray;
			width: 100px;
			height: 100px;
			/*float: left;*/
			position: fixed;
			left: 30px;
			top: 30px;
		}
	</style>
	<body>
		<div class="one">
			<div class="one_11">把红色背景作为父窗口定位的absolute
				<div class="one_12">把蓝色背景作为父窗口定位的absolute
				</div>
			</div>
			<div class="one_13">把红色背景作为父窗口定位的absolute
				</div>
			<div class="one_14">把红色背景作为父窗口定位的absolute
			</div>
		</div>
		<div class="one1">把浏览器窗口作为父窗口的定位absolute</div>
		<div class="one2">不会改变的定位fixed</div>
	</body>
	
</html>

运行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值