Rudra Raina
Rudra Raina

Reputation: 303

My div disappears after I position it as absolute

I know what absolute positioning in CSS is & how it is used, so I thought of playing with it. I created 3 divs mainly and set the position of the .red one as absolute and to my surprise, the .blue one goes missing. Why is that? Shouldn't the .red one be out of the flow and its position should have been altered rather than the .blue ones?

.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>

Upvotes: 1

Views: 1869

Answers (2)

Pranav Rustagi
Pranav Rustagi

Reputation: 2731

This is happening because of out of flow. As you can see in the snippet below, in the first .parent element, .red is visible, whereas .blue is not. The .blue element is present and is hidden behind .red. In the second .parent, the .red element has one more class .change changing the z-index property to -1. This makes the .red hide behind .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>

Upvotes: 2

michaelT
michaelT

Reputation: 1701

Your .red div is above your .blue. For testing, add opacity: 0 to the red one and you will notice that it is still there.

This is because the .red has position: absolute while the blue and green one have position: relative. So they do not affect each other in their positons.

A relative element is positioned relative in its parent. A absolute element is positioned absolute in its parent, where the top left corner is the origin. relative and absolute elements do not affect each other in their positions.

Upvotes: 1

Related Questions