steveo225
steveo225

Reputation: 11892

With a z-index of -1, the after pseudo element is hidden behind background

I made a simple progress bar for an online form. It worked fine, until I added a background color on the containing div. It seems that when z-index is set to -1, it hides behind the background of the parent's parent's parent.

The following JS Fiddle shows the error above what is expected. https://jsfiddle.net/h2e52oux/

What can I do to make the top one work the same as the bottom when there is a background color?

div {
  height: 100px;
}
div.bg {
  background-color: white;
}
ul {
  counter-reset: step;
}
li {
  list-style-type: none;
  width: 25%;
  text-align: center;
  font-style: italic;
  color: #999;
  float: left;
  position: relative;
}
li::before {
  content: counter(step);
  counter-increment: step;
  width: 1.5em;
  text-align: center;
  display: block;
  background: white;
  border: 1px solid #999;
  color: #999;
  margin: 0 auto 5px auto;
}
li:not(:first-child)::after {
  content: '';
  width: 100%;
  height: 3px;
  background: white;
  border: 1px solid #999;
  position: absolute;
  top: 0.5em;
  left: -50%;
  z-index: -1;
}
li.active {
  color: #222;
  font-style: normal;
}
li.active::before,
li.active::after {
  background: #b05d68;
  color: white;
  border: 0;
}
<div class="bg">
  <ul>
    <li class="active">One</li>
    <li class="active">Two</li>
    <li>Three</li>
    <li>Four</li>
  </ul>
</div>
<div>
  <ul>
    <li class="active">One</li>
    <li class="active">Two</li>
    <li>Three</li>
    <li>Four</li>
  </ul>
</div>

Upvotes: 0

Views: 78

Answers (2)

VXp
VXp

Reputation: 12078

In your case it turns out that no matter what number you give to the z-index, adding the lines below are enough to do the work. I set it to the value of -2 on purpose to make it 1 layer below lis but that can be changed as desired. Just the z-index property alone takes no effect because it needs to be accompanied by the position property with the value of anything different than the default static. Setting it to the value of relative is a logical choice since I don't want to break your layout.

div.bg {
  position: relative;
  z-index: -2;
}

Upvotes: 2

Coffee bean
Coffee bean

Reputation: 1504

Try:

div.bg {
  position: relative;
  z-index: -2;
}

z-index only works on positioned elements (position:absolute, position:relative, or position:fixed).

Setting the z-index to -2 means the background div will be stacked below your other content.

Upvotes: 0

Related Questions