CSS箭头在屏幕缩小时上下偏移问题求助
Hey there! Let's fix that jumping arrow issue you're having. The problem comes down to how you're positioning the arrow using percentage margins—here's what's going wrong and how to fix it:
Why the arrow is moving
Your current code uses margin-top: 49% and margin-left: 48% to position the arrow. In CSS, percentage-based margins are calculated relative to the width of the parent element, not its height. So when you shrink the screen width, those margin values change, making the arrow jump up and down.
The fix: Use transform for consistent centering
Instead of relying on percentage margins, we'll use a combination of absolute positioning and transform to keep the arrow centered perfectly, no matter the screen size. Here's the updated CSS:
.arrow-down { width: 100%; margin: 0 auto; text-align: center; position: relative; /* 新增:让伪元素相对于这个容器定位 */ /* 如果需要箭头在视口垂直居中,添加下面这行(根据你的布局调整) */ min-height: 100vh; } .arrow-down::after { content: ""; width: 40px; height: 40px; position: absolute; top: 50%; /* 把箭头左上角移到父元素垂直中心 */ left: 50%; /* 把箭头左上角移到父元素水平中心 */ /* 平移自身宽高的50%,让箭头中心和父元素中心重合,同时保持旋转 */ transform: translate(-50%, -50%) rotate(45deg); -webkit-transform: translate(-50%, -50%) rotate(45deg); /* 兼容旧版webkit浏览器 */ border-right: 4px solid rgb(255, 0, 0); border-bottom: 4px solid rgb(0, 255, 0); animation: 3s arrow infinite ease; }
What this does:
position: relativeon the parent.arrow-downensures the pseudo-element is positioned relative to this container, not the entire page.top: 50%andleft: 50%move the top-left corner of the arrow to the center of the parent.transform: translate(-50%, -50%)shifts the arrow left and up by half its own width/height—this centers the arrow perfectly, and sincetransformpercentages are based on the arrow's own size, it won't change when the screen width does.
Alternative: Fix it to the viewport
If you want the arrow fixed to a specific spot (like the bottom of the screen), use position: fixed instead:
.arrow-down::after { content: ""; width: 40px; height: 40px; position: fixed; bottom: 20px; /* 距离屏幕底部20px */ left: 50%; transform: translateX(-50%) rotate(45deg); -webkit-transform: translateX(-50%) rotate(45deg); border-right: 4px solid rgb(255, 0, 0); border-bottom: 4px solid rgb(0, 255, 0); animation: 3s arrow infinite ease; }
This will keep the arrow locked to the bottom center of the screen, no matter how you resize the window.
Give this a try and your arrow should stay put when you shrink the screen!
内容的提问来源于stack exchange,提问作者Ivan C

