利用 background 和 filter 模糊指定区域

背景知识:background-size: cover;background-attachment:fixed;filter:blur()

难题:

一般,咱们会经过filter:blur()去实现背景高斯模糊,可是缺点很明显,整个背景都模糊了,能不能模糊其中指定的一块呢?好比:css

<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区域呢?
html

尝试:

  • 经过半透明的背景和filter:blur来实现
.content {
  width:50%; 
  height:50%;
  background:rgba(255,255,255,0.5);
  filter:blur(20px)
}

固然效果是不太好的:
git

方案:

  • .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)
}

效果:
github

原理:

background-size:coverbackground-attachment:fixed,这两个属性搭配致使了,父子元素虽然大小不同,可是背景是重合的,即便加上url

margin-left:200px;

改变了位置,背景图仍是重合的,这个时候模糊子元素就像是模糊了父元素背景的某一部分同样,如图:

这是由于:
background-size:coverbackground-attachment:fixed 一块儿被设置时,这就比如给视口设置了一个position:fixed定位的背景图,而后以前设置背景图的元素能够从它的背景中看到一部分视口的背景图,可是其余元素看不到,譬如:3d

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;致使了空白,可是滚动的时候,背景并无滚动,咱们透过元素的滚动能够看到剩余的背景图。code

参考文档:

CSS background-size: cover + background-attachment: fixed clipping background imageshtm

相关文章
相关标签/搜索