Ritesh kumar
Ritesh kumar

Reputation: 45

Z-index on relative positioning

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

Upvotes: 1

Views: 2137

Answers (3)

Mr. Alien
Mr. Alien

Reputation: 157334

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. */
}

Upvotes: 3

Ishank Gupta
Ishank Gupta

Reputation: 1593

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;}

Upvotes: 1

Shyam
Shyam

Reputation: 792

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.

Upvotes: 0

Related Questions