Change the Position of Overlapping Elements with the z-index Property

Change the Position of Overlapping Elements with the z-index Property

position: absolute
Here we are trying to test the z-index , and how it works, by changing overlapping elements.
I am unclear to why we are using position: absolute here, and as mentioned earlier absolute is ideally inside a position: relative ancestor. I removed position: absolute it stops working properly. Need better understanding of this

Your code so far

  div {
    width: 60%;
    height: 200px;
    margin-top: 20px;
  .first {
    background-color: red;
    position: absolute;
    z-index: 2;
  .second {
    background-color: blue;
    position: absolute;
    left: 40px;
    top: 50px;
    z-index: 1;

<div class="first"></div>
<div class="second"></div>

You’re right to question things like that, but the question is really set up to test if you understand how to use the z-index property, and not specifically to talk about positioning per se

So it’s not a representation of best practices or anything, just a set up for testing the z-index

The tests probably then fail as it expects a certain set of CSS, though I’ve not looked at the code yet to see what in particular causes it to fail

1 Like

-To cause the overlapping effect you should change the normal flow of your element.
-By default all element has position: static; which is the normal flow of the element in the browser.
-So to overlap an element you should change it’s position to “relative, absolute or fixed” to be able to use “top, bottom, left and right” css.