背景知識:background-size: cover;
,background-attachment:fixed;
,filter:blur()
難題:
通常,我們會通過filter:blur()
去實現背景高斯模糊,但是缺點很明顯,整個背景都模糊了,能不能模糊其中指定的一塊呢?比如:
<header>
<div class="content"></div>
</header>
header {
width:100vw;
height:100vh;
background:url('https://xianshenglu.github.io/css/img-displayed/frosted-glass-tiger.jpg') no-repeat 0/cover fixed;
}
.content {
width:50%;
height:50%;
background:pink;
}
能不能只模糊 .content
區域呢?
嘗試:
- 通過半透明的背景和
filter:blur
來實現
.content {
width:50%;
height:50%;
background:rgba(255,255,255,0.5);
filter:blur(20px)
}
當然效果是不太好的:
方案:
- 把
.content
的背景換成和父元素一樣,再使用filter:blur()
即:
.content {
width:50%;
height:50%;
background:url('https://xianshenglu.github.io/css/img-displayed/frosted-glass-tiger.jpg') no-repeat 0/cover fixed;
filter:blur(20px)
}
效果:
原理:
background-size:cover
和background-attachment:fixed
,這兩個屬性搭配導致了,父子元素雖然大小不一樣,但是背景是重合的,即使加上
margin-left:200px;
改變了位置,背景圖還是重合的,這個時候模糊子元素就像是模糊了父元素背景的某一部分一樣,如圖:
這是因為:
當 background-size:cover
和background-attachment:fixed
一起被設置時,這就好比給視口設置了一個position:fixed
定位的背景圖,然后之前設置背景圖的元素可以從它的背景中看到一部分視口的背景圖,但是其他元素看不到,譬如:
header {
width:100vw;
height:100vh;
margin-top:200px;
background:url('https://xianshenglu.github.io/css/img-displayed/frosted-glass-tiger.jpg') no-repeat 0 0/cover fixed;
}
仔細看下面的 gif:
header
元素上方的 margin-top:200px;
導致了空白,但是滾動的時候,背景並沒有滾動,我們透過元素的滾動可以看到剩余的背景圖。
參考文檔:
CSS background-size: cover + background-attachment: fixed clipping background images