原文在個人博客 ☞ 實現div毛玻璃背景css
本文介紹一個實現div毛玻璃背景的方法html
CSS3的Filter主要用在圖像的特效處理上,默認值爲none
,還有如下備選項:字體
每一種效果你們能夠本身試試,考慮一下能夠用在哪些方面, 這裏僅僅用到了其中的blur
,幫助實現高斯模糊的效果。ui
兼容性 ☞ caniuseurl
參數默認是0,單位px
,不接受%
,參數值的大小表示屏幕上以多少像素融在一塊兒, 因此值越大越模糊。spa
:before是css中的一種僞元素,可用於在某個元素以前插入某些內容。 用它來添加模糊 ☞ :before和:aftercode
毛玻璃背景上文字內容顯示效果並不理想,不管字體顏色深或淺,看着老是怪怪的...所以還須要加上一層帶色的半透明背景,通常是黑色,或白色。cdn
總體經過三層重疊實現, 最下面是模糊層.blur_box:before
,設置z-index: -2
。 中間是rgba層.rgba
,設置z-index: -1
。 最上面是內容層.blur_box
,設置z-index: 0
。 代碼以下:htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>毛玻璃效果</title>
</head>
<style>
*{
margin: 0;
padding: 0;
}
.bg{
background:url(1.jpg) no-repeat center center fixed;/* 與下面的blur_box:before中的background設置同樣 */
width:100%;
height:100%;
}
.blur_box{
z-index: 0;/* 爲不影響內容顯示必須爲最高層 */
position: relative;
overflow: hidden;
}
.blur_box:before{
content: "";/* 必須包括 */
position: absolute;/* 固定模糊層位置 */
width:300%;
height:300%;
left: -100%;/* 回調模糊層位置 */
top: -100%;/* 回調模糊層位置 */
background:url(1.jpg) no-repeat center center fixed;/* 與上面的bg中的background設置同樣 */
filter: blur(20px);/* 值越大越模糊 */
z-index: -2;/* 模糊層在最下面 */
}
.rgba{
background-color: rgba(0, 0, 0, 0.2);/* 爲文字更好顯示,將背景顏色加深 */
position: absolute;/* 固定半透明色層位置 */
width:100%;
height:100%;
z-index: -1;/* 中間是rgba半透明色層 */
}
.content_text{
text-align: center;
color: rgba(255, 255, 255, 0.8);
padding: 50px 30px;
line-height: 28px;
}
article{
width:40%;
height:300px;
margin:120px auto;
}
</style>
<body
<div class="bg">
<article class="blur_box">
<div class="rgba"></div><!-- 寫在這其實和blur_box:before效果相同,但已經設置過blur_box:before了 -->
<div class="content_text">
<h1>haha</h1>
<p>texttexttexttexttexttexttexttexttext</p>
<p>texttexttexttexttexttexttexttexttext</p>
<p>texttexttexttexttexttexttexttexttext</p>
<p>texttexttexttexttexttexttexttexttext</p>
<p>texttexttexttexttexttexttexttexttext</p>
<p>texttexttexttexttexttexttexttexttext</p>
</div>
</article>
</div>
</body>
</html>
複製代碼
註釋已經寫的很詳細了,但有一點仍是得單獨說一下。由於blur()產生的模糊效果當值越大時,就會有越寬的邊緣漸變過渡,爲了消除(實際上只是讓它看不見),我將模糊層的寬度和高度都變大,再經過top
和left
負值調整位置。blog
.blur_box:before{
content: "";
position: absolute;
width:300%;/* 模糊層的寬度和高度都變大 */
height:300%;
left: -100%;/* 回調模糊層位置 */
top: -100%;
background:url(1.jpg) no-repeat center center fixed;
filter: blur(20px);
z-index: -2;
}
複製代碼
其中.rgba
也可改成白色半透明background-color: rgba(255,255,255,0.2);
,徹底取決於本身,而後相應改變內容的字色。blur()
的參數也能夠根據本身愛好試着改變出想要的效果。