You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使绝对定位内部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 width and height gives the circle a solid base, so the line has a container to fit inside. Pairing equal width/height with border-radius: 50% ensures a perfect circle.
  • Relative positioning on the circle: Changing from absolute to relative means 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:46:06