如何使绝对定位内部div的z-index低于外部绝对定位div?
Hey there! It looks like your current setup is having an issue where the red line extends outside the blue circle, right? That's because your .circle element doesn't have a defined size—it only takes up space equal to its border width, while the inner line is set to a fixed 100px height. Let's adjust the code to get the desired effect:
Fixed Code
.circle { display: inline-block; border: solid 20px blue; border-radius: 50%; /* Use 50% for a perfect circle instead of 51% */ position: relative; /* Switch to relative so the line is positioned inside it */ width: 100px; /* Define a base width for the circle */ height: 100px; /* Match height to width for a circular shape */ z-index: 5; } .line { position: absolute; top: 0; left: 50%; transform: translateX(-50%); /* More reliable horizontal centering */ width: 6px; height: 100%; /* Make the line fill the full height of the circle */ background: red; z-index: -1; }
<div class='circle'> <div class='line'></div> </div>
Key Improvements
- Defined size for the circle: Adding
widthandheightgives the circle a solid base, so the line has a container to fit inside. Pairing equal width/height withborder-radius: 50%ensures a perfect circle. - Relative positioning on the circle: Changing from
absolutetorelativemeans the inner line (which is absolute) will be positioned relative to the circle, not the entire viewport. - Better centering: Using
transform: translateX(-50%)centers the line horizontally without relying on hardcoded negative margins, which is more flexible if you adjust the line's width later. - Full-height line: Setting
height: 100%makes the line stretch from the top to the bottom of the circle, so it doesn't stick out or leave gaps.
With these changes, you'll get a blue circle with a centered red line that stays entirely within the circle's bounds.
内容的提问来源于stack exchange,提问作者GorvGoyl
相关产品推荐
相关产品推荐

