change the position of overlapping elements with the z index property - zilongxuan001/LearnFreecode GitHub Wiki

使用z-index 属性改变重叠元素的位置

理解

当元素的位置重叠了,HTML会默认后来的元素压在原来的元素上面。

然而,使用z-index属性可以设置元素的不同层次,类似phtoshop或PPT的图层概念。

z-index的值必须为正数,值越高越在上面。

练习

原来是蓝色压着红色,因为蓝色是后来的。

给红色元素的classfirst增加一个z-index属性,值设置为2,这样它就能覆盖蓝色的元素。

<style>
  div {
    width: 60%;
    height: 200px;
    margin-top: 20px;
  }
  
  .first {
    background-color: red;
    position: absolute;
    z-index:2;
  }
  .second {
    background-color: blue;
    position: absolute;
    left: 40px;
    top: 50px;
    z-index: 1;
  }
</style>

<div class="first"></div>
<div class="second"></div>

来源

Applied Visual Design: Change the Position of Overlapping Elements with the z-index Property | Learn freeCodeCamp

CHANGELOG

2018-10-25 09:52:58

⚠️ **GitHub.com Fallback** ⚠️