z-index元素堆叠

2022-05-12  本文已影响0人  kevin_lln

通常我们可能会认为HTML页面是个二维的平面,因为页面中的文本、图像或者其它元素都是按照一定顺序排列在页面上的,每个元素之间都有一定的间隙,不会重叠。然而,实际的网页其实是三维的,元素之间可能会发生重叠,我们可以通过z-index属性设置元素的堆叠顺序。

每个元素都有一个默认的z-index属性,将z-index属性与position属性相结合可以创建处类似于ps中的图层效果。z-index属性可以设置元素层叠级别,拥有更高层叠级别的元素会处于层叠级别较低的元素前面。

关于元素层级关系有以下几点需要注意:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>z-index</title>
    <style>
        .box1 {
            width: 400px;
            height: 400px;
            background: darkorange;
            position: absolute;
            left: 50px;
            top: 50px;
            z-index: 1;
        }

        .box2 {
            width: 400px;
            height: 400px;
            background: darkblue;
            position: absolute;
            left: 60px;
            top: 60px;
        }

        .box3 {
            width: 400px;
            height: 400px;
            background: darkcyan;
            position: absolute;
            left: 70px;
            top: 70px;
        }

        .box4 {
            width: 400px;
            height: 400px;
            background: darkgray;
            position: absolute;
            left: 80px;
            top: 80px;
        }

        .box5 {
            width: 400px;
            height: 400px;
            background: darkgreen;
            position: absolute;
            left: 75px;
            top: 75px;
        }
    </style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
<div class="box5"></div>
</body>
</html>

image.png
上一篇 下一篇

猜你喜欢

热点阅读