为什么我写的z-index不生效?( 二 )


<style>  div {    width: 100px;    height: 100px;    border: 1px solid saddlebrown;}  .box1 {    position: relative;    z-index: -1;    background: violet;}  .box2 {    margin-top: -50px;    margin-left: 50px;    background: salmon;}  .box3 {    float: left;    margin-top: -50px;    margin-left: 100px;    background: wheat;}  .box4 {    display: inline-block;    background: greenyellow;    margin-left: -50px;}  .box5 {    position: relative;    z-index:0;    left: 200px;    top: -50px;    background: palevioletred;}  .box6 {    position: relative;    z-index: 1;    left: 250px;    top: -100px;    background: gold}</style></head><body>  <div class="box1">1定位z-index<0</div>  <div class="box2">2块级元素</div>  <div class="box3">3浮动</div>  <div class="box4">4行内元素</div>  <div class="box5">5定位z-index=0</div>  <div class="box6">6定位z-index>0</div></body>

为什么我写的z-index不生效?

文章插图
行内元素的层叠顺序为什么要高于块级元素与浮动元素这个理解起来其实很简单,像border/background属于装饰元素的属性,浮动和块级元素一般用来页面布局,而内联元素一般都是文字内容,并且网页设计之初最重要的就是文字内容,所以在发生层叠时会优先显示文字内容,保证其不被覆盖 。
层叠顺序规则
  • 谁大谁上:当具有明显的层叠水平标示的时候,比如说z-index值,在同一个层叠上下文领域,层叠水平值大的覆盖小的
  • 后来居上:当元素的层叠水平一致、层叠顺序相同的时候,在DOM流中处于后面的元素会覆盖前面的元素 。
z-index
z-index 属性设定了一个定位元素及其后代元素或 flex 项目的 z-order 。当元素之间重叠的时候,z-index 较大的元素会覆盖较小的元素在上层进行显示 。
属性值
  • auto: 默认值,当前值与父级相同
  • <integer>: 整型数字
基本特性
  1. z-index 属性允许为负值 。
  2. z-index 属性支持 CSS3 animation 动画 。
  3. 在 CSS 2.1 的时候,需要配合 position 属性且值不为 static 时使用 。
解惑了解完上面这些内容,现在我们再来看一看前文提到的一些问题
1.为什么我写的z-index没有生效?这个很简单,因为它单独使用时不生效,一定要配合定位属性一起,即只对指定了position属性的元素生效——只要不是默认值static,其他的absolute、relative、fixed都可以使z-index生效 。(在CSS3之后,弹性元素的子元素也可以生效)
2.为什么z-index大的元素却没有盖住z-index小的元素?这里我们可以来看一个有趣的现象
<style>  .box1 {    width: 200px;    height: 100px;    background: red;}  .box2 {    width: 100px;    height: 200px;    background: greenyellow;}</style><div style="position:relative; z-index:auto;">  <div style="position:absolute; z-index:2;" class="box1">box1--z-index=2</div></div>?<div style="position:relative; z-index:auto;">  <div style="position:relative; z-index:1;" class="box2">box2--z-index=1</div></div>
为什么我写的z-index不生效?

文章插图
这么看还挺正常的,z-index值大的在z-index值小的上方 。接下来我们稍微改一改,你就能看到奇怪的现象了

经验总结扩展阅读