在 CSS3 中 z 索引的自动和继承之间的 D 差异



我正在通过CSS3的z-index属性,它有四个属性,auto, number, inline和inherit。我理解数字和内联,但auto和inherit让我感到困惑,因为auto的意思是"将值设置为父值,因为它的默认值",而inherit的意思是"从父值继承"。我谷歌了一下,但没有真正理解。

z-index不被继承;每个元素的默认值为auto。如果您将其更改为inherit,则它将直接从其父节点获取值。

关键是auto不创建一个新的局部堆栈上下文,而inherit,如果父节点有任何数值,确实会创建。

请检查这个例子来更好地理解。您可以看到相同的DOM结构是重复的。在第一个场景中,div auto出现在inherit之前,在另一个场景中;倒。

您可以看到,inherit值的作用等同于实际设置z-index: <number>等于父节点,而auto是默认值,它不会创建新的堆叠顺序,只会按照DOM上确定的默认z顺序显示。如果您将父元素的值设置为-1,那么继承将完全像您将z-index: -1设置为.inherit,使其在两个div上显示在.auto后面。

$('#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>

关于MDN的更多信息https://developer.mozilla.org/en-US/docs/Web/CSS/z-index

如果元素'a'是元素'b'的子元素,则元素'b'称为父元素。如果元素'b'的z-index为5.0,元素'a'的z-index设置为继承,元素'a'也将具有z-index 5.0。这就是继承的意义

最新更新