Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Z-index below text but above background

Tags:

html

css

z-index

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>
like image 444
Scotosaurus Avatar asked Oct 22 '13 16:10

Scotosaurus


People also ask

Does Z Index Working with background image?

No, z-index cannot be applied to a background image.

Can you use Z index without position absolute?

In order for z-index to have any effect at all, it needs to be applied to a positioned element, that means, an element with position relative , absolute , fixed , or sticky . If you don't apply a z-index , the elements will be stacked in the order they are written in the HTML. Check this example: HTML.

Does Z Index work with position relative?

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


1 Answers

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.

like image 199
Josh Crozier Avatar answered Oct 03 '22 04:10

Josh Crozier