0

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>
LovinQuaQua
  • 111
  • 2
  • 12

2 Answers2

1
  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>
mr.Hritik
  • 577
  • 3
  • 19
-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>
Momin
  • 3,200
  • 3
  • 30
  • 48