仅对已定位的元素( position:relativeposition:absoluteposition:fixed )有效,默认值为0,可以为负值。

z-index 的层叠规则

z-index 值从小到大层叠

兄弟元素

  • z-index 值相同时,后面的元素在前面的元素上面
<template>
  <div class="box demo1"></div>
  <div class="box demo2"></div>
</template>

<style scoped>
.box {
  height: 60px;
  width: 60px;
  position: absolute;
}
.demo1 {
  /* z-index 默认为 0 */
  background-color: red;
}
.demo2 {
  /* z-index 默认为 0 */
  background-color: green;
  top: 20px;
  left: 20px;
}
</style>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • z-index 值不同时,z-index 值较小的在下方

CSS【详解】层叠 z-index (含 z-index 的层叠规则,不同样式的层叠效果)_css

<template>
  <div class="box demo1"></div>
  <div class="box demo2"></div>
</template>

<style scoped>
.box {
  height: 60px;
  width: 60px;
  position: absolute;
}
.demo1 {
  background-color: red;
  z-index: 2;
}
.demo2 {
  /* z-index 默认为 0 */
  background-color: green;
  top: 20px;
  left: 20px;
}
</style>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

父子元素

  • 子元素永远在父元素上面
  • 不同父元素里的子元素不能直接比较z-index,当父元素的z-index比较小时,子元素的 z-index无论多大都在下方 !

不同样式的层叠效果

从底部到顶部

  • background-color(永远是最底层)
  • background-image/border
  • 负 z-index
  • block 块状盒子
  • float 浮动盒子
  • inline/inline-block 内联元素/盒子
  • z-index:auto 或看成 z-index:0 的元素
  • 正 z-index