titlu titlu - 3 months ago 13
CSS Question

D difference between z-index's auto and inherited in CSS3

I am gong through the z-index property of CSS3 and it has got four properties , auto , number , inline and inherit. I understand number and inline but auto and inherit confuse me as auto mean "sets the value as parent's value as it's default value" and inherit means "inherits the value from parent". I googled but didn't really understand it.

Answer

z-index is not inherited; the default value for every element is auto. If you change it to be inherit then it will grab the value from its parent directly.

The key is that auto does not create a new local stacking context, while inherit, if the parent had any numerical value, will indeed.

Please check this example to get a better understanding. You can see the same DOM structure is duplicated. On the first scenario, div auto comes before inherit and on the other one; it's inverted.

You can see that the inherit value works equally as actually setting z-index: <number> equal to the parent, while auto is the default value that does not create a new stacking order and will simply display on the default z order as per determinated on the DOM. If you make the parent's value -1, then the inheritance will be exactly as if you set z-index: -1 on .inherit making it display behind .auto on both divs.

$('#button0').click(function(e){
  $('.parent').css('z-index', '0');
});
$('#button1').click(function(e){
  $('.parent').css('z-index', '1');
});
$('#button-1').click(function(e){
  $('.parent').css('z-index', '-1');
});
.parent{
  position: relative;
  z-index: 1;
}
.parent > div{
  position: absolute;
}
.auto{
  z-index: auto; /* default value */
}
.inherit{
  z-index: inherit;  
}

/* --------------------- */
/* presentational styles */
.auto{
  background: green;
}
.inherit{
  top: 100px;
  background: red;
}
.parent{
  width: 200px;
  height: 200px;
  opacity: 1;
  margin: 10px;
  background: yellow;
  display: inline-block;
}
.parent > div{
  width: 100px;
  height: 100px;
  opacity: 0.95;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  first auto and then inherit on DOM
  <div class="auto">auto</div>
  <div class="inherit">inherit</div>
</div>

<div class="parent">
  first inherit and then auto on DOM
  <div class="inherit">inherit</div>
  <div class="auto">auto</div>
</div>

<div>
  <label>Change z-index of parent</label>
  <button id="button-1">To -1</button>
  <button id="button0">To 0</button>
  <button id="button1">To 1</button>
</div>

More information on MDN https://developer.mozilla.org/en-US/docs/Web/CSS/z-index

Comments