当对 `.surrounding-image` 使用 `top` 百分比值却无明显位移时,根本原因在于其父容器 `.planets-container` 高度塌陷(仅约39px),导致 `top: 30%` 实际仅计算为十几像素;绝对定位元素脱离文档流,不会撑开父容器高度。
在 CSS 布局中,top(以及 right/bottom/left)属性仅对已定位元素(即 position 为 relative、absolute、fixed 或 sticky)生效——这一点您已正确设置(.surrounding-image 拥有 position: absolute)。但关键被忽略的是:百分比值的计算基准取决于包含块(containing block)的高度。
对于 position: absolute 元素,其包含块是最近的 position 不为 static 的祖先元素(此处即 .planets-container)。而 top: 30% 表示“向上偏移其包含块高度的 30%”。若 .planets-container 自身高度极小(例如仅由内边距或子元素 margin “偶然”撑开的几十像素),那么 30% 就微乎其微,视觉上几乎不可见——这正是您观察到“top 不工作”的真实原因。
? 验证方法:在浏览器开发者工具中检查 .planets-container 的 computed height,大概率会显示一个远小于视口的值(如 39px)。
✅ 正确解决方案:显式定义 .planets-container 的高度,使其具备足够且可控的参考尺寸:
立即学习“前端免费学习笔记(深入)”;