CSS中z-index属性的使用方法和示例介绍

z-index属性介绍

  • 只有设置了定位我们才会使用到该z-index属性,如:固定定位相对定位绝对定位

  • 定位元素默认的z-index属性值是0

  • 如果2个定位的元素都没有设置z-index属性,后者会覆盖到前者。

  • 如果2个定位的元素都设置了z-index属性,并且数值一样大还是后者会覆盖到前者。

  • z-index属性的属性值大的就会覆盖小,就是设置元素的层级。

z-index属性实践

  • 用实践证明这句话,如果2个定位的元素都没有设置z-index属性,后者会覆盖到前者。

  • 代码块

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>z-index属性</title>
  <style>  
    div{
      width: 200px;
      height: 200px;
    } 
     .div1{
       background-color: red;
       position: relative;
       top: 50px;
       left: 50px;
     }
     .div2{
       background-color: slateblue;
       position: relative;
       left: 100px;
     }
    
  </style>
</head>

<body>
    <div></div>
    <div></div>
</body>

</html>

结果图:

<img alt=\"CSS中z-index属性的使用方法和示例介绍\” alt=\”1.png\” data-tag=\”bdshare\” src=\”https://www.freexyz.cn/d/file/20200929/9e5b2f25108e48003c62c5a0bb8d8436.png\” title=\”1580309859298789.png\” />

  • 用实践来证明这句话,如果2个定位的元素都设置了z-index属性,并且数值一样大还是后者会覆盖到前者。

  • 代码块

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>z-index属性</title>
  <style>  
    div{
      width: 200px;
      height: 200px;
    } 
     .div1{
       background-color: red;
       position: relative;
       top: 50px;
       left: 50px;
       z-index: 2;
     }
     .div2{
       background-color: slateblue;
       position: relative;
       left: 100px;
       z-index: 2;
     }
    
  </style>
</head>

<body>
    <div></div>
    <div></div>
</body>

</html>

结果图:

8ec9d8c962a3cbb8a6709164e50bae04

  • 用实践来证明这句话,z-index属性的属性值大的就会覆盖小,就是设置元素的层级。

  • 代码块

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>z-index属性</title>
  <style>  
    div{
      width: 200px;
      height: 200px;
    } 
     .div1{
       background-color: red;
       position: relative;
       top: 50px;
       left: 50px;
       z-index: 3;
     }
     .div2{
       background-color: slateblue;
       position: relative;
       left: 100px;
       z-index: 2;
     }
    
  </style>
</head>

<body>
    <div></div>
    <div></div>
</body>

</html>

结果图:

ff2115ee54550cbd77094ae123867387

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容