css blur background

CSS:Glass Background 毛玻璃特效

Rene Wu 2022/09/27 09:38:22
1214

使用 CSS 的背景濾鏡 backdrop-filter 屬性,就能製作出毛玻璃磨砂半透明效果。

先設定好 html 的內容:

  • 容器
    • 卡片
      • 標題
      • 內文
<div class="container">
  <div class="card">
    <h2>CSS Glass Background</h2>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
  </div>
</div>

接下來就開始設定 CSS 樣式:

#body

將背景直接設定在 body 裡,並在圖片加上濾鏡 blur 模糊效果,數字越大模糊效果越強烈。

body {
  background: url(https://images.unsplash.com/photo-1453032037654-1f17dd472a6c)
    no-repeat;
  background-attachment: fixed; /* 讓背景固定,即便元素的內容滾動,背景也不會隨著元素移動 */
  background-size: cover;
  background-position: center center;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  backdrop-filter: blur(6px); /* 背景濾鏡設定為 blur */
  margin: 0 auto;
}

#容器

使容器繼承父元素 body 的背景,但維持預設無濾鏡原樣式,再添加陰影讓容器自然融入畫面。

.container {
  max-width: 40%;
  box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.4); 
  border-radius: 20px;
  position: relative;
  background: inherit; /* 容器的背景繼承父元素,但不設製 blur 效果 */
  overflow: hidden;
}

#卡片

為卡片添加透明度 65% 的黑色背景,文字設定為白色。

.card {
  color: #ffffff;
  padding: 30px;
  background-color: rgba(0, 0, 0, 0.65); /* 卡片設定透明度65%背景 */
}

#標題與文字

最後將標題與文字的字級、行高、間距設定好就完成了。

h2 {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 16px;
}
p {
  font-size: 16px;
  line-height: 1.5;
}

看看效果吧!

#關於 backdrop-filter

背景濾鏡 backdrop-filter 屬性有多種效果可以設製,也可以多種疊加,範例如下:

/* 关键词值 */
backdrop-filter: none;

/* 指向 SVG 滤镜的 URL */
backdrop-filter: url(commonfilters.svg#filter);

/* <filter-function> 滤镜函数值 */
backdrop-filter: blur(2px);
backdrop-filter: brightness(60%);
backdrop-filter: contrast(40%);
backdrop-filter: drop-shadow(4px 4px 10px blue);
backdrop-filter: grayscale(30%);
backdrop-filter: hue-rotate(120deg);
backdrop-filter: invert(70%);
backdrop-filter: opacity(20%);
backdrop-filter: sepia(90%);
backdrop-filter: saturate(80%);

/* 多重滤镜 */
backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);

/* 全局值 */
backdrop-filter: inherit;
backdrop-filter: initial;
backdrop-filter: revert;
backdrop-filter: unset;

詳細說明可以至下方 MDN 網站查看唷!

參考來源:

Rene Wu