前端之 position的fixed和sticky的区别,含页面小测试

position的fixed和sticky的区别

fixed相对于相对于视口(viewport,浏览器窗口)进行偏移,即定位基点是浏览器窗口。不管视口如何滚动,它的位置始终不变。

fixed如果搭配top、bottom、left、right这四个属性一起使用,表示元素的初始位置是基于视口计算的,否则初始位置就是元素的默认位置。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			.box{
				position: fixed;
				width: 200px;
				height: 200px;
				border: 1px solid #0000FF;
				
			}
			.warp{
				height: 3000px;
				background-color: antiquewhite;
			}
			.box_out{
				width: 400px;
				height: 400px;
				border: 1px solid #0000FF;
			}
		</style>
	</head>
	<body>
		<div class="warp">
			<div class="box_out">
				<div class="box"></div>
			</div>
		</div>
	</body>
</html>

随着插入图片描述
在这里插入图片描述
而sticky则是在目标区域内随着页面的滚动而保持在固定位置,超出这个区域后就就随着目标区域滚动。

sticky生效的前提是,必须搭配top、bottom、left、right这四个属性一起使用,不能省略,否则等同于relative定位,不产生"动态固定"的效果。原因是这四个属性用来定义"偏移距离",浏览器把它当作sticky的生效门槛。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			.box{
				position: sticky;
				width: 200px;
				height: 200px;
				border: 1px solid #0000FF;
				top: 2px;
			}
			.warp{
				height: 3000px;
				background-color: antiquewhite;
			}
			.box_out{
				width: 400px;
				height: 400px;
				border: 1px solid #0000FF;
			}
		</style>
	</head>
	<body>
		<div class="warp">
			<div class="box_out">
				<div class="box"></div>
			</div>
		</div>
	</body>
</html>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 14
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
position: sticky;和fixed都是CSS中的定位属性,用于控制元素的位置。 position: fixed;将元素固定在页面的特定位置,不随页面滚动而移动。它脱离了文档流,并且会覆盖其他元素。使用fixed定位时,可以通过设置top、right、bottom、left属性来指定元素的具体位置。 position: sticky;相当于relative和fixed的结合体。当修饰的目标元素在屏幕中可见时,它表现为relative定位,即按照正常文档流的位置进行布局。但当目标元素即将超出屏幕边界时,它会切换为fixed定位,即固定在屏幕上的特定位置。这使得元素在滚动时能够在一定范围内保持在屏幕上,提供更好的用户体验。 需要注意的是,position: sticky;在某些旧版浏览器中可能不被支持。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [固定定位(fixed)和粘性定位(sticky)的比较](https://blog.csdn.net/weixin_51093047/article/details/126923647)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [JS解决position:sticky的兼容性问题的方法](https://download.csdn.net/download/weixin_38741950/13206331)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值