I can't wrap my head around the concept of z-index. For some reason the gray box appears at the very bottom. Then comes the black box and on top of them, the red box. It should be precisely the other way around. Thx for any help!
HTML:
<div id="gray-box">
<div id="black-box"><div>
<div id="red-box"></div>
</div>
CSS:
#gray-box {
position: relative;
z-index: 2;
background-color: gray;
width: 100%;
height: 4rem;
}
#black-box {
position: relative;
z-index: 1;
background-color: black;
width: 20rem;
height: 4rem;
}
#red-box {
position: relative;
z-index: 0;
background-color: red;
width: 20rem;
height: 4rem;
}
First off, you were missing a closing slash for your black box closing div, that was throwing the DOM off.
Secondly, the gray box is the parent of the other two divs, so it is always going to be underneath them, unless you take the child divs completely out of the flow, and give them a negative z-index. For example, I've given the black and red boxes a position:absolute
, and changed the gray box to the default position: static
, so the red and black box are not being treated like children of the gray box anymore:
#gray-box {
position: static;
background-color: gray;
width: 100%;
height: 4rem;
}
#black-box {
z-index: -1;
background-color: black;
width: 20rem;
height: 4rem;
position: absolute;
top: 20px; left: 20px
}
#red-box {
z-index: -2;
background-color: red;
width: 20rem;
height: 4rem;
position: absolute;
top: 30px; left: 30px;
}
<div id="gray-box">
<div id="black-box"></div>
<div id="red-box"></div>
</div>