0


前端:让一个div悬浮在另一个div之上

使用 CSS 的

position

属性和

z-index

属性

首先,将第二个

div

元素的

position

属性设为

relative

absolute

。这样可以让该元素成为一个定位元素,使得后代元素可以相对于它进行定位。

然后,将要悬浮的

div

元素的

position

属性设为

absolute

,并设置

z-index

属性的值大于第二个

div

元素的值。

例如,下面的示例中,第二个

div

元素的

position

属性设置为

relative

,要悬浮的

div

元素的

position

属性设置为

absolute

,并且设置了

z-index

属性的值为

1

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <div style="position: relative; width: 200px; height: 200px;
            background-color: lightgray;">
            <p>这是第二个 div 元素</p>
        </div>

        <div style="position: absolute; z-index: 2; top: 50px; left: 50px;
            width: 100px; height: 100px; background-color: red;">
            <p>这是要悬浮的 div 元素</p>
        </div>
    </body>
</html>
标签: 前端 html css

本文转载自: https://blog.csdn.net/weixin_46001736/article/details/134838021
版权归原作者 雯0609~ 所有, 如有侵权,请联系我们删除。

“前端:让一个div悬浮在另一个div之上”的评论:

还没有评论