css3父元素模糊不影响子元素

ゞ 浴缸里的玫瑰 2022-07-11 05:43 689阅读 0赞

说一下css3父元素模糊不影响子元素的效果。在使用css3的filter属性设置背景模糊的时候,我们通常想到的做法是写如下的代码:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title></title>
  6. <style type="text/css"> .test { width:420px; height:420px; filter:blur(5px); background:url('http://www.zi-han.net.img.800cdn.com/theme/hplus/img/a3.jpg') no-repeat; background-size: cover; } </style>
  7. </head>
  8. <body>
  9. <div style="width: 300px;height: 300px;position: relative;">
  10. <div class="test">
  11. <img src="http://www.zi-han.net.img.800cdn.com/theme/hplus/img/a2.jpg">
  12. </div>
  13. </div>
  14. </body>
  15. <script type="text/javascript" src="user.js"></script>
  16. </html>

但是这样设置之后,页面的效果确实父元素和子元素都模糊了!

这里写图片描述

去网上了了些资料,很多都说改 z-index=-1 但是我加到 .test 缺没有效果,后面才知道其实这是通过伪类来实现的,上面代码中的css样式改成如下:

  1. .test { width:420px; height:420px; }
  2. .test::before{ content: ""; position: absolute; filter:blur(5px); z-index: -1; background:url('http://www.zi-han.net.img.800cdn.com/theme/hplus/img/a3.jpg') no-repeat; width: 100%; height: 100%; top: 0px; left: 0px; background-size: cover; overflow:hidden; }

这样效果就对了:

这里写图片描述

在这里还需要注意一个细节,为了边缘不被模糊化,需要设置 overflow:hidden; 要不效果就是这样了:

这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,689人围观)

还没有评论,来说两句吧...

相关阅读