Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

z-index an absolutely positioned element under a relatively positioned one

I am trying to put an absolutely positioned element under a relatively positioned one. The blue box HAS to be relatively positioned due to constraints within the site development.

Imagine a speech bubble is the blue box, the bubble's tail is the :after pseudo-element. I need the green box to go behind both of these as it is to hold a background for these two elements.

div.layer01 {
    background-color: blue;
    position: relative;
    z-index: 10;
}
div.layer01:after {  /* This is the tail of the bubble */
    display: block;
    background-color: red;
    content: '\00a0';
    width: 30px;
    height: 30px;
    position: absolute; 
    right: 20px;
    top: 50px;
    border: 3px #fff solid;
}    

/* This should be behind the tail and the blue box (bubble) */
div.layer01 div.layer02 { 
    background-color: green;
    width: 320px;
    height: 125px;
    display: block;
    position: absolute; 
    z-index: 5;
}
<div class="layer01"> <!-- speech bubble -->
    <div class="layer02">Why isn't this below the blue?</div>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus non dolor quis leo malesuada pharetra at in massa. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
</div>

FIX:

Took the element I wanted positioned out of the relatively positioned element then wrapped the contents into a new div. Adds mark up but seems this was the only way.

like image 985
beingalex Avatar asked Jan 17 '23 16:01

beingalex


1 Answers

Edit: I was misinformed, negative indexes were introduced in CSS2.1. This solution is still correct, though my comments about it being a hack are not.

Child elements, even if absolutely positioned can't be below their parent element unless you use a hack.

The hack is to remove the z-index property from the parent and give the child element a negative z-index

http://jsfiddle.net/uZdy3/1/

div.layer01 {
    background-color: blue;
    position: relative;
}
div.layer01:after {  /* This is the tail of the bubble */
    display: block;
    background-color: red;
    content: '\00a0';
    width: 30px;
    height: 30px;
    position: absolute; 
    right: 20px;
    top: 50px;
    border: 3px #fff solid;
}    

/* This should be behind the tail and the blue box (bubble) */
div.layer01 div.layer02 { 
    background-color: green;
    width: 320px;
    height: 125px;
    display: block;
    position: absolute; 
    z-index: -5;
}

It would be much better to refactor your layout to avoid this hack, though.

like image 75
JaredMcAteer Avatar answered May 01 '23 20:05

JaredMcAteer