当前位置: 移动技术网 > IT编程>网页制作>HTML > z-index不起作用的大坑

z-index不起作用的大坑

2020年07月11日  | 移动技术网IT编程  | 我要评论

 

 一对兄弟节点,insert和parent,parent有两个子节点subtop和subbottom,展现的结果是想让subtop在insert上面,subbottom在insert下面,

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        .insert{
            position: relative;
            z-index:100;
            background: green;
            width:300px;
            height:300px;
            top:100px;
        }
        .parent{
            /*position:relative;
            z-index: 1000;*/
            width:200px;
            height:200px;
            /*left:0;
            top:-50px;*/
            border:1px solid #eee;
        }
        .subbottom{
            position:relative;
            z-index: 50;
            width:200px;
            height:200px;
            background: red;
            top:-100px;
            left:0;
 
        }
        .subtop{
            position: relative;
            z-index:1100;
            width:100px;
            height:100px;
            left:0;
            top:0;
            background: blue;
        }
    </style>
</head>
<body>
    <div class="insert"></div>
    <div class="parent">
        <div class="subtop"></div>
        <div class="subbottom"></div>
    </div>
</body>
</html>

其实原理也很简单,就是利用了z-index的覆盖问题,在写的过程中我发现无论怎么改变,insert的z-index总是无效的,于是百度了一下z-index无效的情况,一共有三种:
1、父标签 position属性为relative;

2、问题标签无position属性(不包括static);

3、问题标签含有浮动(float)属性。

这样也很好理解为什么parent设置了position和z-index之后insert的z-index就会失效的问题了,他的解决办法有是三个:


1、position:relative改为position:absolute;

2、浮动元素添加position属性(如relative,absolute等);

3、去除浮动。

所以,去掉parent的position和z-index,达到了我想要的效果,如下图所示:
 

本文地址:https://blog.csdn.net/hcrw01/article/details/85986115

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网