z-index失效问题解析

问题源自于我在原网页中加入了一个下拉菜单,在原先单独的下拉菜单代码里z-index并没有问题换到了复杂的网页里z-index显示混乱,由此我进行了相关的了解

我们先看一段代码,可以复制下来自己看一下

先给出结果图:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        div{
            width:200px;
            height:200px;
            padding:20px;
        }
        .one,.two,.three,.four{
            position:absolute;
        }
        .one{
            background:red;
            border:5px solid black;
            top:100px;
            left:200px;
            z-index:10;
        }
        .two{
            background:green;
            border:5px solid black;
            top:50px;
            left:75px;
            z-index:100;
        }
        .three{
            background:blue;
            border:5px solid black;
            top:125px;
            left:25px;
            z-index:150;
        }
        .four{
            background:purple;
            border:5px solid yellow;
            top:200px;
            left:350px;
            z-index:50;
        }
       
/*.five{*/  /*width:400px;*/  /*height:400px;*/  /*background:green;*/  /*border:5px solid cornflowerblue;*/  /*margin-top:10px;*/  /*margin-left:350px;*/  /*z-index:250;*/ /*}*/
</style></head><body><div class="one"> z-index=10 <div class="two">z-index=100</div> <div class="three">z-index=150</div></div><div class="four">z-index=50</div>

<!--<div class="five">z-index=60</div>-->
<h1>对于结果来说,虽然four的z-index值小于two和three的,但因为它俩在one里所以其实真正的z-index分别为10.100和10.150还是小于four的z-index</h1></body></html> 


我们可以看到两个包在one里的divz-index设置值都比four这个div大但是结果确是它俩在four下面这是因为它俩都在one里面z-index值在one的基础上的所以实际为10.100和10.150,还是比four的150小

 

我们再把代码里的div five加上去,把上面代码里的注释去掉就行

 

.five{
    width:400px;
    height:400px;
    background:green;
    border:5px solid cornflowerblue;
    margin-top:10px;
    margin-left:350px;
    z-index:250;
}

运行结果如下:

图里也说了新加的five在所有div下面,这是由于他的z-index并没有起作用,而没起作用是因为没有position的设置,下面我们给five设置一个position

 

.five{
    position:relative;
    width:400px;
    height:400px;
    background:green;
    border:5px solid cornflowerblue;
    margin-top:10px;
    margin-left:350px;
    z-index:250;
}

再看结果

 

position的值可以随便设置但必须有一个值,relative、position、fixed都行,这样z-index最大的five就显示在其他div上面了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值