1

I am newbie to HTML. I searched whether z-index works on relative positioned elements or not, and I found yes it works.

But the problem is when i am trying its not getting stacked.

<style>
.div0{position:relative;top:0px;left:0px;width:100%;height:auto;z-index:1;}
.div1{position:relative;top:0px;left:0px;width:100%;height:auto;z-index:1;}
.div2{position:relative;top:0px;left:0px;width:100%;height:auto;z-index:2;}
</style>
</head>
<body>
<div class="div0">
    <div class="div1">Text One</div>
    <div class="div2">Text Two</div>
</div>
</body>

Fiddle

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278

3 Answers3

3

First of all lets refactor your CSS, you won't need width:100%; and height: auto; as width of the block level element is always auto but it takes entire horizontal space unless if it's floated or it's turned to inline-block or inline and as far as height is concerned, it's auto by default so you don't need to define it.

Secondly, if you are trying to stack the div on on another than consider using position: absolute; for the child elements instead of position: relative;, if you want to stick with position: relative; than you will need to define the top value in negative.

Demo

.div2{
    position:relative;
    left:0px;
    z-index:2; 
    top: -15px;
}

But make sure that position: relative; does change the position of the element, but it reserves the space physically in the flow, whereas, position: absolute; won't.


Also, if you want to apply some same properties to your child elements, you can use selectors like

.div0, .div1, .div2 {
   /* Common properties here */
}

.div2 {
   /* Override common properties, or you can define unique ones as well. */
}
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
  • For more information on how CSS positioning works, you can refer my answer [here](http://stackoverflow.com/questions/20718577/how-css-positions-work-why-absolute-elements-stack-up-on-each-other-instead-of) – Mr. Alien Jan 13 '14 at 06:39
1

Update the position of .div1 and .div2 to absolute.

.div1{position:absolute;top:0px;left:0px;width:100%;height:auto;z-index:1;}
.div2{position:absolute;top:0px;left:0px;width:100%;height:auto;z-index:2;}
Ishank Gupta
  • 1,575
  • 1
  • 14
  • 19
  • By absolute it can be done, but what about relative? – Ritesh kumar Jan 13 '14 at 06:33
  • 1
    @Ishank Gupta Ritesh Kumar asking with relative position.. you said answer with absolute position – Haji Jan 13 '14 at 06:33
  • absolute positioning is best for such implementation, you need to shift the element to overlap the other div if you want to implement it using relative positioning. – Ishank Gupta Jan 13 '14 at 06:37
0

relative positioned elements top & left properties works from current x-y position of element. In this case, you can use negative top to stack div2 over div1.

Shyam
  • 782
  • 5
  • 12