我的 div 在我将其定位为绝对后消失了

My div disappears after I position it as absolute

我知道 CSS 中的绝对定位是什么以及它是如何使用的,所以我想玩一下。我主要创建了 3 个 divs,并将 .red 的位置设置为绝对位置,令我惊讶的是,.blue 的位置不见了。这是为什么? .red 不应该在流程之外并且它的位置应该被改变而不是 .blue 吗?

.red{
  background-color: red;
  height: 30px;
  width: 30px;
  position: absolute;
}
.blue{
  background-color: blue;
  height: 30px;
  width: 30px;
}
.green{
  background-color: green;
  height: 30px;
  width: 30px;
}
<div class="parent">
    <div class="red">
    </div>
    <div class="blue">
    </div>
    <div class="green">
    </div>
</div>

您的 .red div 高于您的 .blue。为了测试,将 opacity: 0 添加到红色的,你会注意到它仍然存在。

这是因为.redposition: absolute,而蓝色和绿色有position: relative。所以他们在各自的位置上不会互相影响。

一个 relative 元素在其父元素中被定位为相对absolute 元素在其父元素中被定位为 absolute,其中左上角是原点。 relativeabsolute元素在它们的位置上不会相互影响。

发生这种情况是因为 out of flow。正如您在下面的代码片段中看到的,在第一个 .parent 元素中,.red 可见,而 .blue 不可见。 .blue 元素存在并隐藏在 .red 后面。在第二个 .parent 中,.red 元素又多了一个 class .change,将 z-index 属性 更改为 -1。这使得 .red 隐藏在 .blue..

后面

.parent {
  position: relative;
}

.red {
  background-color: red;
  height: 30px;
  width: 30px;
  position: absolute;
}

.blue {
  background-color: blue;
  height: 30px;
  width: 30px;
}

.green {
  background-color: green;
  height: 30px;
  width: 30px;
}

.change {
  z-index: -1;
}
<div class="parent">
  <div class="red">
  </div>
  <div class="blue">
  </div>
  <div class="green">
  </div>
</div>

<br/><br/>

<div class="parent">
  <div class="red change">
  </div>
  <div class="blue">
  </div>
  <div class="green">
  </div>
</div>