如何修复使用百分比top定位的fixed固定块在屏幕高度缩小时重叠的问题
问题根源
你推测的方向是对的:两个元素的top使用百分比值,是相对于视口高度计算的,视口高度缩小时百分比对应的偏移量会同步缩小。而第一个.rectangle的高度是固定的216px,当视口高度足够小时,第一个元素的底部位置会超过第二个元素的top值,就会出现重叠。
最优解决方案(推荐)
把两个元素放到同一个固定定位的父容器中统一控制位置,子元素用正常流排布即可,完全避免重叠问题,也能实现整体垂直居中的效果。
1. 修改HTML结构
给两个块元素加外层父容器:
<div class="fixed-sidebar-right"> <div id="navShareLink" class="rectangle" style="display: none"> Here are just pictures with links </div> <div id="scrollTopButtonBlog" class="top-button-article" style="display: none"> There is also a text and a picture </div> </div>
2. 调整CSS样式
新增父容器样式,同时删掉原有两个类里和定位相关的重复属性:
/* 新增父容器样式 */ .fixed-sidebar-right { position: fixed; right: 12px; /* 实现整体垂直居中 */ top: 50%; transform: translateY(-50%); /* 子元素垂直排列,固定间距 */ display: flex; flex-direction: column; gap: 20px; /* 两个块之间的间距可自行调整 */ z-index: 999; } /* 调整原有样式,删除定位相关属性 */ .rectangle { transition: opacity 0.5s; padding: 5px; height: 216px; width: 48px; background-color: rgba(0, 0, 0, 0.1); border-radius: 24px; } .top-button-article { transition: opacity 0.5s; cursor: pointer; padding: 5px; }
不改HTML的替代方案
如果不想修改HTML结构,可以直接修改第二个元素的top属性,用calc计算其位置,保证永远在第一个元素下方:
.top-button-article { z-index: 999; transition: opacity 0.5s; cursor: pointer; padding: 5px; position: fixed; /* 27%是第一个元素的top,216px是第一个元素高度,20px是自定义间距 */ top: calc(27% + 216px + 20px); right: 12px; }
该方案的局限性是如果后续修改了第一个元素的高度,需要同步调整calc里的数值,不如父容器方案灵活。
内容的提问来源于stack exchange,提问作者user17428261
相关产品推荐
相关产品推荐

