DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS特效代碼
用純 CSS 做出圖片磨砂玻璃(毛玻璃)效果
編輯:CSS特效代碼     

線上展示:https://hovertree.com/texiao/css/13/

毛玻璃就是磨砂玻璃,能隱約透出身後的景象,帶點朦朧美感,也讓介面多了層次。

用 Photoshop 做一張全景毛玻璃圖當然最省事,但那樣就沒什麼可玩的了。既然要用 CSS,核心武器只有一個:filter: blur()。真正的巧思在於怎麼讓模糊層和背景圖「對齊」。

結構

<div class="container">
 <div class="frosted-glass"></div>
 <img class="weather" src="cloudy.png">
</div>

外層 div 當容器,負責鋪風景背景圖;內層 div 是毛玻璃主體;最後一張 img 顯示天氣圖示。

容器層

.container {
  width: 287px;
  height: 285px;
  background-image: url(background.png);
  background-repeat: no-repeat;
  background-attachment: fixed;
  overflow: hidden;
}

關鍵是 background-attachment: fixed。設成 fixed 之後背景不隨元素捲動,子元素在繼承這層背景時,就等於變成了一個「視窗」,移到哪裡就看見背景的哪一部分。

毛玻璃層

.frosted-glass {
  width: 287px;
  height: 285px;
  background: inherit;
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -ms-filter: blur(5px);
  -o-filter: blur(5px);
  filter: blur(5px);
  filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius=4, MakeShadow=false);
}

background: inherit 是整個效果的靈魂——直接沿用父元素的背景,再搭配 fixed,就能做到「從毛玻璃後面看世界」的效果。因為用的是 inherit,模糊區域可以是全幅,也可以只覆蓋上半部或某一角,非常自由。

最後那行 filter: progid:DXImageTransform... 是給 IE6~9 的相容寫法。

天氣圖示

.weather {
  width: 80px;
  height: 80px;
  margin-top: -200px;
  margin-left: 100px;
  position: relative;
  display: block;
}

我偏好用 margin 做元素內的定位,而不是把圖示扔到 absolute 裡。理由是 margin 對頁面回流(reflow)的影響有限,父元素尺寸或位置變動時的副作用較小;反過來若用 absolute,一旦父容器尺寸改變就得重新計算座標,維護成本高。

這裡給 position: relative 有兩個作用:一是讓圖示的層級高於預設 static 的兄弟元素,二是保留 margin 的定位能力。另外記得先設成 display: block,否則行內元素的 margin 縱向值不會生效。

完整程式碼

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title>使用 CSS 實現圖片磨砂玻璃效果</title>
 <style>
.frosted-glass-hovertree {
  width: 466px;
  height: 284px;
  background: inherit;
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -ms-filter: blur(5px);
  -o-filter: blur(5px);
  filter: blur(5px);
  filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius=4, MakeShadow=false);
}
.container-hovertree {
  width: 466px;
  height: 284px;
  background-image: url(https://hovertree.com/hvtimg/201512/agagq0or.jpg);
  background-repeat: no-repeat;
  overflow: hidden;
}
.tipshovertree {
  height: 80px;
  margin-top: -200px;
  margin-left: 100px;
  position: relative;
  display: block;
}
 </style>
</head>
<body>
 <div class="container-hovertree">
 <div class="frosted-glass-hovertree"></div>
 <div class="tipshovertree">玻璃</div>
 </div>
</body>
</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved