如何显示被其他div覆盖的div

3

<!DOCTYPE html>
<html lang="en">
<head>
 <title>Title</title>
 <style>
  .red {
   height: 200px;
   background-color: red;
  }
  .green {
   height: 300px;
   background-color: green;
   width: 200px;
  }
  .yellow {
   height: 400px;
   background-color: yellow;
  }
 </style>
</head>
<body>
 <div class="red">
  <div class="green"></div>
 </div>
 <div class="yellow"></div>
</body>
 
<script>
 
</script>
</html>

如上代码所示,绿色div的高度为300px。然而,由于被黄色div覆盖,它并没有完全显示。

因此,我想问如何使绿色div完全显示,就像下面这样。

5个回答

2
将你的样式中添加一个 z-index 属性。另一个很棒的资源是:w3schools 此外,将 .green 的高度更改为 600px,以覆盖整个屏幕:

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Title</title>
  <style>
    .red {
      height: 200px;
      background-color: red;
      z-index: 0;
    }
    
    .green {
      height: 600px;
      position: absolute;
      background-color: green;
      width: 200px;
      z-index: 99;
    }
    
    .yellow {
      height: 400px;
      background-color: yellow;
      z-index: -1;
    }
  </style>
</head>

<body>
  <div class="green"></div>
  <div class="red"></div>


  <div class="yellow"></div>
</body>

<script>
</script>

</html>

这将使绿色的 div 盖在所有 z-index 更低的元素之上,因为 10 > 1。最初的回答。

2

.red {
  height: 200px;
  background-color: red;
}

.green {
  height: 300px;
  background-color: green;
  width: 200px;
  display: inline-table;
}

.yellow {
  height: 400px;
  background-color: yellow;
}
<div class="red">
  <div class="green"></div>
</div>
<div class="yellow"></div>

你可以使用display: inline-table
.green {
    height: 300px;
    background-color: green;
    width: 200px;
    display: inline-table;
}

1

像这样玩转z-index:

       .red {
       height: 200px;
       background-color: red;
          z-index: 1;
      }
      .green {
       height: 300px;
       background-color: green;
       width: 200px;
          z-index: 99; 
          float:left; 
      }
      .yellow {
       height: 400px;
       background-color: yellow;
          z-index: -1;
      }
<div class="red">
  <div class="green"></div>
 </div>
 <div class="yellow"></div>


z-index在你的情况下完全无用,它们只能与定位元素一起使用...将它们删除,你将得到相同的输出。诀窍在于浮动元素。 - Temani Afif

1
你只需要将绿色的div定位即可,无需其他操作。

.red {
  height: 200px;
  background-color: red;
}

.green {
  height: 300px;
  background-color: green;
  width: 200px;
  position: relative;
}

.yellow {
  height: 400px;
  background-color: yellow;
}
<div class="red">
  <div class="green"></div>
</div>
<div class="yellow"></div>

或者红色的:

.red {
  height: 200px;
  background-color: red;
  position: relative;
}

.green {
  height: 300px;
  background-color: green;
  width: 200px;
}

.yellow {
  height: 400px;
  background-color: yellow;
}
<div class="red">
  <div class="green"></div>
</div>
<div class="yellow"></div>

默认情况下,绘图顺序将先绘制绿色和红色,然后按照树的顺序绘制黄色,但将其中一个定位将使该定位后绘制。


以下是一些相关问题,以获取有关绘画订单的更多详细信息:

为什么position:relative;似乎会改变z-index?

为什么使用absolute position会导致div位于顶部?


1
只需为红色类添加 position: relative

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接