1

In this code, I think div1 should be floating above div2. Because div1 is applied float:left attribute. But the result is that div2 is floating above div1. Why?

div {
    width:100px;
    height:100px;
    border:1px solid gray;
    font-size:0.7em;
}

.blue {
    background-color: blue;
}
.green {
    background-color: green;
    float:left
}
.red {
    background-color: red;
    position:relative;
    left:10px;
}
<div class="blue"></div>
<div class="green div1"></div>
<div class="red div2"></div>

The result:

enter image description here

Sercan
  • 4,739
  • 3
  • 17
  • 36
Ohing
  • 17
  • 3

1 Answers1

0

The float: left style is used to justify an element to the left. For an element to render above or below another element, you must assign a z-index style; it appears above the other element with the higher z-index style.

div {
  width:100px;
  height:100px;
  border:1px solid gray;
  font-size:0.7em;
}
.blue {
  background-color: blue;
}
.green {
  background-color: green;
  float: left;
  z-index: 1;  /* This style has been added. */
}
.red {
  background-color: red;
  position: relative;
  left: 10px;
  z-index: -1; /* This style has been added. */
}
<div class="blue"></div>
<div class="green"></div>
<div class="red"></div>

References
Sercan
  • 4,739
  • 3
  • 17
  • 36
  • the first z-index you added has no effect because the element is not positioned, only z-index:-1 has an effect here – Temani Afif Jan 12 '22 at 08:05
  • I purposely added it so that the post owner can understand the difference between the styles. – Sercan Jan 12 '22 at 08:08
  • what "difference"? this can be misleading because z-index *alone* is not enough to identify the painting order – Temani Afif Jan 12 '22 at 08:10