Scotosaurus
Scotosaurus

Reputation: 353

Z-index below text but above background

I'm trying to get a div to show as a partial background below the inline content of is containing div but above the background of its container. If I set the z-index of just the partial background to -1 it appears behind the background. But if i set the containing divs z-index to 1 while the contained div's z-index is -1 it displays as desired.

Can someone explain to me why this is and if this is a reliable method or not?

.container {
  position: relative;
  width: 80%;
  height: 18px;
  padding: 6px 10px;
  background: #666;
  z-index: 1;
}

.partialbg {
  position: absolute;
  left: 0px;
  top: 0px;
  height: 30px;
  width: 80%;
  background: #0CC;
  z-index: -1;
}
<div class="container">Text here
  <div class="partialbg"></div>
</div>

Upvotes: 6

Views: 4793

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240928

The reason this is occurring, is because there is a child and a parent. If you set a z-index on the parent, the child is going to be the same, since the z-index is stacked.

Thus, by setting a z-index of 1 on the parent, the child is now also 1.

It is systematically impossible for the child to be behind the parent, as that doesn't make any sense. However, the text is a sibling of the child. By setting a z-index of -1 on the child, there is essentially no effect between the child and the parent, however since the sibling is effected, the child now goes behind the sibling.

Upvotes: 7

Related Questions