Css 简明教程

CSS - Layers

在 CSS 中,你可以创建不同级别的图层。CSS * z-index* 属性可以与 * position* 属性相结合来创建图层效果。

  • z-index* 属性规定元素的堆叠顺序。你可以指定哪个元素应该放在上面,哪个应该放在下面。

一个 * z-index* 属性可以帮助你创建更复杂的网页布局。

CSS Layers - With z-index Property

以下示例演示如何使用 * z-index* 属性创建图层。具有较高 z-index 值的元素位于具有较低 z-index 值的元素之上 −

<html>
<head>
<style>
   .box1 {
      position: absolute;
      height: 100px;
      width: 100px;
      background-color: red;
      z-index: 1;
      padding: 3px;
      left: 10px;
      top: 10px;
   }
   .box2 {
      position: absolute;
      height: 100px;
      width: 100px;
      background-color: lightblue;
      z-index: 2;
      padding: 5px;
      margin: 10px;
      left: 50px;
      top: 30px;
   }
   .box3 {
      position: absolute;
      height: 100px;
      width: 100px;
      background-color: yellow;
      z-index: 3;
      padding: 5px;
      margin: 20px;
      left: 80px;
      top: 50px;
   }
   p {
      margin-top: 200px;
   }
</style>
</head>
<body>
   <p>The element with z-index value of 1 appears behind the elements with the z-index value of 2 and 3.</p>
   <div class="box1">
      CSS z-index: 1
   </div>
   <div class="box2">
      CSS z-index: 2
   </div>
   <div class="box3">
      CSS z-index: 3
   </div>
</body>
</html>

CSS Layers - Images and Text

以下示例演示如何使用 * z-index* 属性创建图层。z-index 较高的元素位于 z-index 较低的元素之上 −

<html>
<head>
<style>
   img {
      height: 200px;
      width: 200px;
      position: absolute;
      left: 0px;
      top: 0px;
      z-index: 2;
      margin: 5px;
   }
   h1 {
      margin-top: 30px;
      z-index: 1;
      color: red;
   }
</style>
</head>
<body>
   <img src="images/shop.png">
   <h3>Tutorialspoint</h3>
</body>
</html>

CSS Layers - Without z-index Property

以下示例演示如何不使用 * z-index* 属性创建图层 −

<html>
<head>
<style>
   .box1 {
      position: absolute;
      height: 210px;
      width: 210px;
      background-color: red;
      padding: 10px;
      left: 10px;
      top: 10px;
   }
   .box2 {
      position: absolute;
      height: 150px;
      width: 150px;
      background-color: lightblue;
      padding: 10px;
      margin: 10px;
      left: 30px;
      top: 30px;
   }
   .box3 {
      position: absolute;
      height: 100px;
      width: 100px;
      background-color: yellow;
      padding: 5px;
      margin: 10px;
      left: 60px;
      top: 60px;
   }
</style>
</head>
<body>
   <div class="box1">
      Box 1
   </div>
   <div class="box2">
      Box 2
   </div>
   <div class="box3">
      Box 3
   </div>
</body>
</html>