CSS——固定定位和Z-index值

本文详细介绍了CSS中的固定定位,这是一种相对于浏览器窗口的定位方式,使得元素在页面滚动时始终保持在特定位置。同时,文章还探讨了Z-index属性,用于控制元素的堆叠顺序,数值越大,元素在层叠中越靠前。理解这两个概念对于创建交互式网页设计至关重要,特别是解决元素覆盖问题时。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

固定定位
就是相对浏览器窗口定位,绝对定位的一种特殊形式。它以浏览器窗口作为参照物来定义网页元素,当position属性取值为fixed时,即为固定定位。

当对元素设置固定定位后,它将脱离标准文档流的控制,始终依据浏览器窗口来定义自己的显示位置。页面如何滚动,这个盒子显示的位置不变。

固定定位的元素跟父亲没有任何关系,只认浏览器,完全脱标,不占有位置,不随着滚动条滚动。

		.backtop{
			position: fixed;
			width: 100px;
			height: 100px;
			background-color: gray;
			bottom: 100px;
			right: 30px;
			text-align: center;
			line-height: 30px;
			color: white;
			text-decoration: none;
		}
	</style>
</head>
<body>
	<a href="" class="backtop">返回顶部</a>
	<img src="images/wuyuetian.jpg" alt="" />
	<img src="images/wuyuetian.jpg" alt="" />
	<img src="images/wuyuetian.jpg" alt="" />
	<img src="images/wuyuetian.jpg" alt="" />
</body>

返回顶部就是固定定位。

	<style type="text/css">
		*{
			margin: 0;
			padding: 0;
		}
		.nav{
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 60px;
			background-color: #333;
		}
	</style>
</head>
<body>
	<div class="nav"></div>
	<img src="images/wuyuetian.jpg" alt="" />
	<img src="images/wuyuetian.jpg" alt="" />
	<img src="images/wuyuetian.jpg" alt="" />
	<img src="images/wuyuetian.jpg" alt="" />
</body>

固定定位脱标。

IE6不兼容固定定位。

Z-index值
z-index值表示谁压着谁,数值大的压盖住数值小的。
z-index的默认属性值是0,取值越大,定位元素在层叠元素中越居上。如果取值相同,则根据书写顺序后来居上。后面数字不能加单位。
只有定位了的元素才有z-index值。不管相对定位、绝对定位、固定定位都可以使用z-index值,浮动的东西不能使用。
如果大家都没有z-index值,或者z-index值都一样,那么谁写在html后面,谁在网页上能压盖住别人。定位了的元素永远能够压住没有定位的元素。

从父现象。
z-index没有单位。
z-index: 988;

	<style type="text/css">
		*{
			margin: 0;
			padding: 0;
		}
		.box1{
			width: 200px;
			height: 200px;
			background-color: yellowgreen;
		}
		.box2{
			width: 200px;
			height: 200px;
			background-color: skyblue;
		}
	</style>
</head>
<body>
	<div class="box1"></div>
	<div class="box2"></div>
</body>
	<style type="text/css">
		*{
			margin: 0;
			padding: 0;
		}
		.box1{
			width: 200px;
			height: 200px;
			background-color: yellowgreen;
			position: absolute;
			top: 100px;
			left: 100px;
			z-index: 999;
		}
		.box2{
			width: 200px;
			height: 200px;
			background-color: skyblue;
			position: absolute;
			top: 180px;
			left: 180px;
			z-index:555;
		}
	</style>
</head>
<body>
	<div class="box1"></div>
	<div class="box2"></div>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值