如何实现元素相对容器固定定位:底部按钮固定、中间文本滚动
I see the issues you're facing—let's fix this step by step to meet all your requirements:
Key Problems in the Original Code
- The left button was rendering behind the text (since it appeared earlier in the HTML flow, it had a lower stacking context).
- The right button could overlap with the container's scrollbar when text overflows.
- We need to ensure buttons stay anchored to the container's bottom no matter the text length or scrolling state.
Corrected Code
HTML (no changes needed here, included for completeness)
<div class="container"> <div class="button-wrapper left"> <div class="button"></div> </div> <div class="text"> <div class="line"></div> <div class="line"></div> <div class="line"></div> <div class="line"></div> <div class="line"></div> <div class="line"></div> <div class="line"></div> <div class="line"></div> <div class="line"></div> <div class="line"></div> </div> <div class="button-wrapper right"> <div class="button"></div> </div> </div>
Updated CSS
.container { width: 400px; height: 200px; border: 1px solid; position: relative; overflow: auto; margin-bottom: 4rem; padding-right: 16px; /* Optional: prevents text from hiding under scrollbar */ } .line { height: 8px; width: 100%; background-color: grey; border-radius: 8px; margin-bottom: 20px; } .text { padding: 5px 50px; } .button-wrapper { position: absolute; bottom: 4px; z-index: 10; /* Ensures buttons sit above the text content */ } .button { width: 32px; height: 32px; background-color: orange; } .left { left: 4px; } .right { right: 20px; /* Adjusted to avoid scrollbar overlap */ }
What Changed & Why
z-index: 10on.button-wrapper: This lifts the buttons above the text content, so they're always visible even when scrolling.- Adjusted
right: 20pxfor the right button: Moves the button left enough to avoid overlapping the container's scrollbar (you can tweak this value based on your browser's scrollbar width). - Optional
padding-right:16pxon.container: Ensures your text doesn't get cut off under the scrollbar when it appears.
How This Meets Your Requirements
✅ Buttons stay fixed at the container's bottom while text scrolls
✅ Scrollbar appears on the outer container (.container)
✅ Buttons remain anchored to the bottom even when text is shorter than the container height
内容的提问来源于stack exchange,提问作者ghostCoder
相关产品推荐
相关产品推荐

