gignu
gignu

Reputation: 2485

z-index not affecting the order in which elements are displayed

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

Upvotes: 2

Views: 60

Answers (4)

Roskow
Roskow

Reputation: 410

Read this post, I think it will clear up your misunderstanding. It explains that the z-index of a parent does not matter with regard to the child element. I think this is what you are trying to achieve by setting the z-index of the parent higher than the children.

How to make child element higher z-index than parent?

Upvotes: 1

symlink
symlink

Reputation: 12209

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>

Upvotes: 2

Aaron Osborn
Aaron Osborn

Reputation: 59

Your closing <div> is incorrect on the 'black-box' element. Make sure you close with a forward slash </div>

Upvotes: 0

Norbert Biro
Norbert Biro

Reputation: 9

I think the issue is that you have a div that's not closed. Here: <div id="block-box"><div> there's a missng / in the closing div tag.

Here's a working version if this is what you were looking for. https://codepen.io/norbertbiro/pen/pozxpQP

Upvotes: 0

Related Questions