美文网首页程序员
CSS3 层层递进的阴影效果

CSS3 层层递进的阴影效果

作者: 万千钧 | 来源:发表于2017-02-27 13:32 被阅读0次

    项目中往往需要一种层层递进的阴影遮盖效果

    就像这样:


    目标效果

    层层递进的阴影效果

    通常我们会采取给每个盒子设置box-shadow

    
    div{
      width:100px;
      height:100px;
      background:#e3e3e3;
      border:1px solid #333;
      box-shadow:0 0 50px rgba(0,0,0,0.5);
    }
    
    

    结果并不满意


    直接设置box-shadow

    那是不是通过设置不同的z-index也可以决定阴影的遮盖顺序呢

    div {
      width: 100px;
      height: 100px;
      background: #e3e3e3;
      border: 1px solid #333;
      box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
    }
    div:nth-child(2) {
      z-index:999;
    }
    
    设置z-index后的结果

    并没有什么改善

    那到底如何才能达到目标效果呢

    我们要先去理解z-index
    MDN中对z-index的定义
    其中明确规定了

    只有当 position 不为 static 的时候, z-index 才是有效的

    所以只要给盒子添加 position: relative 属性, 就能正常控制阴影效果了

     div {
      position: relative;
      width: 100px;
      height: 100px;
      background: #e3e3e3;
      border: 1px solid #333;
    }
    
    div:nth-child(2) {
      box-shadow: 0 0 50px rgba(0, 0, 0, 0.5);
      z-index: 999;
    }
    
    设置 position: relative 后

    结论

    z-index只在position不为 static 的时候生效
    z-index 数值大的盒子阴影遮盖 z-index 数值小的

    转载请注明出处

    相关文章

      网友评论

        本文标题:CSS3 层层递进的阴影效果

        本文链接:https://www.haomeiwen.com/subject/zmkzwttx.html