您的位置:首页 > 其它

filter:blur() 实现毛玻璃效果

2017-01-03 14:25 429 查看
使用玻璃效果比普通效果中的文字更易阅读,而且整体美观。在过去,我们通常把文本框区域的背景做模糊处理,随后使用一整张背景。不仅消耗性能,而且在HTML方面难以修改维护。



我们用filter:blur()这个css滤镜来实现。目前所以的浏览器,除了IE,其他浏览器上均能实现。

1. 以下是HTML片段


<body>
<main>
<blockquote>
"The only way to get rid of a temptation is to yield to it.
Resist it, and your soul grows sick with longing for the things
it has forbidden to itself, with desire for what its monstrous
laws have made monstrous and unlawful."
</blockquote>
</main>
</body>

2. 给body与main伪元素设置背景,background-attachment的值设置为fixed。这个很重要。不管元素父级是谁,一旦设置为fixed,其背景是相对于整个窗口的视角来定位,与绝对定位的fixed相同。这样方便模糊后的图片与原图完美匹配。

body,main::before{
background-image: url("images/background.jpg");
background-repeat: no-repeat;
background-size: cover;
background-attachment:fixed;
}


3.接下来给main的伪元素设置模糊值。虽然现代浏览器能够支持,比如Firefox,Chrome等,但如果想要在IE浏览器上实现,这个时候我们不得不专门为它想个解决办法,最方便的就是直接给它增加背景色,而不是模糊化。

main::before{
content: '';
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
margin: -30px;
z-index: -1;
-webkit-filter: blur(20px);
filter: blur(20px);
}


4. 最后稍微优化一下代码,整理布局,一个毛玻璃效果就实现了,很简单。

body {
min-height: 100vh;
box-sizing: border-box;
margin: 0;
padding-top: calc(50vh - 6em);
font: 150%/1.6 Baskerville, Palatina,serif;
}

body,main::before {
background: url("images/background.jpg") 0 / cover fixed;
}

main {
position: relative;
margin: 0 auto;
padding: 1em;
max-width: 23em;
background: hsla(0,0%,100%,.25) border-box;
overflow: hidden;
border-radius: .3em;
box-shadow: 0 0 0 1px hsla(0,0%,100%,.3) inset,
0 .5em 1em rgba(0,0,0,0.6);
text-shadow: 0 1px 1px hsla(0,0%,100%,.3);
}

main::before{ content: ''; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: -30px; z-index: -1; -webkit-filter: blur(20px); filter: blur(20px); }

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: