skip to Main Content

how can i overlay the blue div over the yellow div? I tried to add a relative position to the outer div, but i doesnt work.

.c1{
  padding:25px;
  background: blue;
  position: relative;
  top: 0;
  left: 0;
  z-index: 10;
  
}
.c2{
top: 0; 
left: 0;
width: 100%;
height: 100%;
z-index: 1;
  background: yellow;
}
<div class="container">
  <div class="c1">
    <div class="c2">
      Hallo Welt
    </div>
  </div>
</div>

2

Answers


    1. You can have a child element behind his parent element with z-index. You have to give z-index:-1; and position:absolute; to the child div.

    2. Also I’m sharing the link of a article for your reference that describes how you can use the stacking order of elements to allow the z-index to be negative in order to place an element behind it’s parent.
      What No One Told You About Z-Index

    .c1{
      padding:25px;
      background:blue;
      position:relative;
      top: 0;
      left: 0;
    }
    
    .c2{
      position:absolute;
      top: 0; 
      left: 0;
      width: 100%;
      height: 100%;
      background: yellow;
      z-index:-1;
    }
    <div class="container">
      <div class="c1">
        <div class="c2">
          Hallo Welt
        </div>
      </div>
    </div>
    Login or Signup to reply.
  1. According to CSS specifications, when using the position: absolute value, the element will always look for a positioned parent element (i.e. an element with position: relative) to act as a reference point. If no positioned parent is found, the element will default to the document body.

    Additionally, when working with the position property, the z-index property only works on positioned elements (i.e. elements with a position value other than static).

    .c1 {
      padding: 25px;
      background: blue;
      position: relative;
      top: 0;
      left: 0;
      z-index: 10;
    }
    
    .c2 {
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 2;
      background: yellow;
      position: absolute;
    }
    <div class="container">
      <div class="c1">
        <div class="c2">
          Hallo Welt
        </div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search