---
title: "Liquid Glass CSS 與 SVG 程式碼：做出真正的折射"
description: "Liquid Glass 網頁程式碼：各瀏覽器通用的 CSS 玻璃層，加上在 Chromium 做出真折射的 SVG feDisplacementMap 濾鏡。"
url: https://liquidglassdesign.com/zh-TW/blog/liquid-glass-css-svg
language: zh-Hant
published: 2026-11-18
updated: 2026-11-20
author: "Liquid Glass Design"
tags: ["Web 前端","程式碼"]
translations:
  en: https://liquidglassdesign.com/blog/liquid-glass-css-svg.md
  zh-Hans: https://liquidglassdesign.com/zh/blog/liquid-glass-css-svg.md
  ja: https://liquidglassdesign.com/ja/blog/liquid-glass-css-svg.md
  hi: https://liquidglassdesign.com/hi/blog/liquid-glass-css-svg.md
---

# Liquid Glass CSS 與 SVG 程式碼：做出真正的折射

> Liquid Glass 網頁程式碼：各瀏覽器通用的 CSS 玻璃層，加上在 Chromium 做出真折射的 SVG feDisplacementMap 濾鏡。

網頁上的 Liquid Glass（液態玻璃）程式碼分成兩部分：一層所有瀏覽器都能用的 CSS 玻璃（模糊、色調、邊緣亮光、光澤），以及一個 SVG `feDisplacementMap` 濾鏡，負責彎折元素背後的像素。到 2026 年 11 月為止，彎折的部分要透過 `backdrop-filter: url()` 才畫得出來，而且只有 Chromium 核心的瀏覽器支援，所以請把它當成疊在 CSS 層上的加強效果。

## 為什麼只用 backdrop-filter 模糊，看起來就是玻璃擬態

`backdrop-filter: blur()` 會把面板背後的一切均勻抹糊，這就是設計師從 2020 年起稱為玻璃擬態的霧面卡片風格。Apple 的材質比較像一片厚透鏡：透過平坦中央看到的背景大致清晰，到了圓弧邊緣才彎折，面向光源那一側的邊緣還有一道亮光。我們的 [Liquid Glass 是什麼](https://liquidglassdesign.com/zh-TW/what-is-liquid-glass)說明文章把兩者的差別講得更細，[Liquid Glass 與玻璃擬態比較](https://liquidglassdesign.com/zh-TW/blog/liquid-glass-vs-glassmorphism)則附了一份用截圖分辨兩者的檢查清單。落到程式碼上，簡單講就是：模糊給你的是霧面，「液態」的部分來自邊緣的位移。

想看動起來的範例，可以看 Piqo Studio 的 [Liquid Glass Design Video](https://liquidglassdesign.com/gallery/liquid-glass-design-video)（工作室形容這件作品是把 Liquid Glass 帶到網頁上），以及 Ho3ein 的 [Liquid Glass Buttons hover effect](https://liquidglassdesign.com/gallery/liquid-glass-buttons-hover-effect)。

![Piqo Studio 網站的手機畫面，半透明的膠囊形頁首和 Book a call 按鈕疊在一張書桌照片上](https://cdn.liquidglassdesign.com/gallery/21ecd13d-8a84-80a5-b651-c45832691275.webp)

*Liquid Glass Design Video by Piqo Studio。* [在作品集中查看](https://liquidglassdesign.com/gallery/liquid-glass-design-video)
![純白背景上的淡藍色膠囊形 Start Now 按鈕，附一個向右的箭頭](https://cdn.liquidglassdesign.com/gallery/e03ba758-2a3a-45a3-822a-64bdc0dbe983.png)

*Liquid Glass Buttons - Hover Effect by Ho3ein。* [在作品集中查看](https://liquidglassdesign.com/gallery/liquid-glass-buttons-hover-effect)
## 第 1 層：所有瀏覽器都能用的 Liquid Glass CSS

每位訪客都會看到這一層，所以就算完全沒有折射，它也得像個完成品：淡淡一層色調、加了飽和度的小幅模糊、頂部邊緣一道 inset 亮光、一條極細邊框，再用偽元素加一層柔和光澤。

```css
.glass {
  position: relative;
  border-radius: 40px;
  color: #fff;
  background: rgb(255 255 255 / 0.10);
  -webkit-backdrop-filter: blur(6px) saturate(160%);
  backdrop-filter: blur(6px) saturate(160%);
  box-shadow:
    inset 0 1px 0 rgb(255 255 255 / 0.6),   /* lit top rim */
    inset 0 -1px 0 rgb(255 255 255 / 0.15), /* faint bottom rim */
    inset 0 0 0 1px rgb(255 255 255 / 0.2), /* hairline edge */
    0 10px 30px rgb(0 0 0 / 0.25);          /* lift off the page */
}

.glass::before {
  content: "";
  position: absolute;
  inset: 0;
  border-radius: inherit;
  pointer-events: none;
  background: radial-gradient(120% 70% at 25% 0%, rgb(255 255 255 / 0.35), transparent 55%);
}
```

`-webkit-` 那一行要留著。根據 MDN 的相容性資料，Safari 從 Safari 9 開始只支援帶前綴的屬性，一直到 Safari 18 才推出不帶前綴的版本，而舊版 Safari 現在仍有人在用。

模糊要小。半徑一大，就又回到毛玻璃，第 2 層的折射也沒剩下清晰的東西可以彎折。

同一個 class 也能用在 `<button>` 上。我們的 [Liquid Glass 按鈕指南](https://liquidglassdesign.com/zh-TW/blog/liquid-glass-button)另外補上了懸停、按下和焦點狀態。

## 第 2 層：SVG 折射濾鏡

`feDisplacementMap` 會依照從第二張圖（也就是位移貼圖）讀到的數值，移動輸入影像的每一個像素。Filter Effects 規範把它定義為 `P'(x,y) ← P(x + scale * (XC(x,y) - .5), y + scale * (YC(x,y) - .5))`。紅色通道控制水平移動，綠色控制垂直移動。通道值 128（0.5）代表「不動」，`scale` 則是最大的位移量，單位是像素。

所以要做的事，就是畫出一張貼圖：形狀平坦的中央是中性灰，靠近邊緣處則沿著邊緣法線方向推動像素。濾鏡如下：

```html
<svg width="0" height="0" aria-hidden="true" style="position:absolute">
  <filter id="lg-refract" x="0" y="0" width="100%" height="100%"
          color-interpolation-filters="sRGB">
    <feImage id="lg-map" x="0" y="0" preserveAspectRatio="none" result="map" />
    <feDisplacementMap in="SourceGraphic" in2="map" scale="60"
                       xChannelSelector="R" yChannelSelector="G" />
  </filter>
</svg>

<div class="glass">Liquid Glass</div>
```

別拿掉 `color-interpolation-filters="sRGB"`。這個屬性預設是 `linearRGB`，而規範會把它套用到貼圖輸入（`in2`）上。在線性色彩空間裡，中性值 128 就不再等於 0.5，玻璃底下的所有東西都會偏離中心。

貼圖本身用 canvas 產生最方便。這個函式用的是到圓角矩形的有號距離，所以膠囊、卡片和圓形都適用：

```js
function makeDisplacementMap(w, h, r, bezel) {
  const canvas = document.createElement("canvas");
  canvas.width = w;
  canvas.height = h;
  const ctx = canvas.getContext("2d");
  const img = ctx.createImageData(w, h);

  // Signed distance to a rounded rectangle: negative inside, positive outside.
  const sdf = (x, y) => {
    const qx = Math.abs(x - w / 2) - (w / 2 - r);
    const qy = Math.abs(y - h / 2) - (h / 2 - r);
    return Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - r;
  };

  for (let y = 0; y < h; y++) {
    for (let x = 0; x < w; x++) {
      const inset = -sdf(x, y); // distance in from the edge
      let dx = 0, dy = 0;
      if (inset > 0 && inset < bezel) {
        const nx = sdf(x + 1, y) - sdf(x - 1, y); // gradient points outward
        const ny = sdf(x, y + 1) - sdf(x, y - 1);
        const len = Math.hypot(nx, ny) || 1;
        const t = 1 - inset / bezel; // 1 at the rim, 0 where the flat top starts
        const strength = t * t;
        dx = (-nx / len) * strength; // sample toward the center near the rim
        dy = (-ny / len) * strength;
      }
      const i = (y * w + x) * 4;
      img.data[i] = 128 + dx * 127;
      img.data[i + 1] = 128 + dy * 127;
      img.data[i + 2] = 128;
      img.data[i + 3] = 255;
    }
  }
  ctx.putImageData(img, 0, 0);
  return canvas.toDataURL();
}
```

`bezel` 是彎折從邊緣往內延伸的距離。平方衰減讓中央保持平坦，最強的彎折則落在最外緣。Kube.io 那篇用 CSS 和 SVG 做折射的文章更進一步，針對不同的表面輪廓，從司乃耳定律推導出曲線；做按鈕和各種 bar 的話，這條比較簡單的曲線就夠用了。

## 第 3 層：只在畫得出來的地方開啟折射

```css
.glass.is-refracting {
  backdrop-filter: url(#lg-refract) blur(1px) saturate(160%);
}
```

```js
const isChromium =
  navigator.userAgentData?.brands?.some((b) => b.brand === "Chromium") ?? false;

const glass = document.querySelector(".glass");
if (isChromium) {
  const { width, height } = glass.getBoundingClientRect();
  const map = document.getElementById("lg-map");
  map.setAttribute("width", width);
  map.setAttribute("height", height);
  map.setAttribute("href", makeDisplacementMap(Math.round(width), Math.round(height), 40, 24));
  glass.classList.add("is-refracting");
}
```

改用腳本檢查、不用 `@supports`，原因有兩個。第一，`url()` 是 `backdrop-filter` 的合法語法（MDN 有列出來），所以就算瀏覽器最後什麼都畫不出來，解析器還是會接受它，而 `@supports` 只會去問解析器。第二，根據 MDN，`navigator.userAgentData` 是 Chromium 獨有的 API，所以檢查 brand 是成本低、也相當可靠的判斷依據。

貼圖必須和元素一樣大。元素尺寸改變時就重新產生貼圖，而且要加上 debounce，因為逐像素的迴圈並不便宜。

## 2026 年 11 月，backdrop-filter: url() 在哪裡能用

- 桌面版和 Android 上的 Chrome、Edge、Opera、Brave 以及其他 Chromium 核心瀏覽器都畫得出來。
- Safari 不行。WebKit bug 245510「backdrop-filter: url(#some-svg-filter) doesn't work with SVG filters like feDisplacementMap」從 2022 年 9 月開到現在。一位貢獻者在 2026 年 7 月到 9 月間提交了附帶測試的 patch，但撰寫本文時，這個 bug 的狀態仍是 NEW。
- Firefox 接受 `backdrop-filter` 裡的 `url()` 濾鏡（Firefox 121 修正了一個迴歸錯誤），但只限它的 GPU 算繪器畫得出來的濾鏡。一位 Mozilla 工程師在 bug 1972363 裡解釋，backdrop 這條路徑「不支援繪製沒有 GPU 加速的濾鏡」，而 `feImage` 加上 `feDisplacementMap` 正好屬於這一類，所以效果會直接失效，也不會有任何提示。
- iPhone 和 iPad 上的每個瀏覽器都是 WebKit，除非是 Apple 在歐盟允許的其他瀏覽器引擎，所以 iOS 上的 Chrome 一樣不會折射。

## 如果 Safari 和 Firefox 也需要折射

用 `filter: url()` 把位移套用在元素自己擁有的內容上，三大引擎都能用。限定 Chromium 的只有 backdrop 這條路徑。Sam Asante 的 headless React 透鏡元件（本站資源頁收錄為 [Real liquid glass for the web](https://liquidglassdesign.com/resources/real-liquid-glass-for-the-web)）和 Aave 的文章「Building Glass for the Web」都採用這種做法。代價是你折射的是玻璃背後內容的副本（一張圖片、一個主視覺區塊、一條滑桿軌道），浮動面板底下那個即時的頁面則折射不到。兩份資料都提到針對 Safari 的變通做法：Safari 會依濾鏡 ID 快取濾鏡輸出，所以每次更新都得換一個 ID；而且 Safari 不會對播放中的 `<video>` 套用 SVG 濾鏡。

我們自己的開源 React 函式庫 [Liqui](https://liqui.design/?utm_source=liquidglassdesign.com&utm_medium=referral&utm_campaign=blog_css_svg) 把這種做法包成了元件。在 `LiquiBackdrop` 裡，每個玻璃表面在 Safari 和 Firefox 會折射那塊背景的副本，在 Chromium 則折射即時頁面；在它外面，表面會變成霧面。設定方式請看我們的 [Liquid Glass React 元件指南](https://liquidglassdesign.com/zh-TW/blog/liquid-glass-react-components)。

想要現成的 Chromium 版本，Shu Ding 那套複製貼上就能用的 [Liquid Glass SVG filters](https://liquidglassdesign.com/resources/liquid-glass-svg-filters) 用 JavaScript 組出同樣的 `feImage` 加 `feDisplacementMap` 組合。如果你用 React，我們的 [Liquid Glass React 函式庫比較](https://liquidglassdesign.com/zh-TW/blog/liquid-glass-react-libraries)依做法整理了各種選擇。

## 上線前的檢查清單

- 關掉折射之後，玻璃看起來依然沒問題。所有 Safari 和 Firefox 訪客都只會看到第 1 層。
- 玻璃上的文字放在它可能遇到的最雜亂背景上，對比也要過關，光在你的主視覺圖片上過關還不夠。
- 濾鏡有加上 `color-interpolation-filters="sRGB"`。
- 位移貼圖和元素尺寸一致，只在尺寸改變時重新產生，不會每個影格都重做。
- 折射由腳本檢查來開啟，不靠 `@supports`。
- 針對 `prefers-reduced-transparency` 和 `prefers-contrast: more` 準備了實心的備援樣式。[網頁效能與備援指南](https://liquidglassdesign.com/zh-TW/blog/liquid-glass-web-performance-fallbacks)裡有對應的分級 CSS。
- 玻璃只用在少數幾個控制項上，沒有每張卡片都套。每個 `backdrop-filter` 都會重新讀取並過濾它背後的內容。

在調整 `scale` 和 `bezel` 之前，先看看設計師怎麼處理同一個問題。Voicu Apostol 的 [Liquid Glass Switch](https://liquidglassdesign.com/gallery/liquid-glass-switch) 用 Figma 的 Glass 效果製作，圓鈕是一片比軌道還高的透明透鏡，只有細細一圈亮邊，幾乎沒有色調；圓鈕壓過軌道的地方，軌道邊緣明顯彎折。像這樣彎折範圍小、邊緣明亮，控制項中間的東西就不會變形。

![標著 Dark 的深色切換開關，透明玻璃圓鈕超出軌道，並讓軌道邊緣彎折](https://cdn.liquidglassdesign.com/gallery/23acd13d-8a84-80be-a2c8-f90b7fa0ecfa.webp)

*Liquid Glass Switch by Voicu Apostol。* [在作品集中查看](https://liquidglassdesign.com/gallery/liquid-glass-switch)
*版本、設定與數據核對於 2026 年 11 月 14 日。*

## 參考資料

- https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter
- https://github.com/mdn/browser-compat-data/blob/main/css/properties/backdrop-filter.json
- https://github.com/mdn/browser-compat-data/blob/main/api/Navigator.json
- https://developer.mozilla.org/en-US/docs/Web/CSS/@supports
- https://drafts.csswg.org/filter-effects-1/#feDisplacementMapElement
- https://kube.io/blog/liquid-glass-css-svg/
- https://bugs.webkit.org/show_bug.cgi?id=245510
- https://bugzilla.mozilla.org/show_bug.cgi?id=1868479
- https://bugzilla.mozilla.org/show_bug.cgi?id=1972363
- https://developer.apple.com/support/alternative-browser-engines/
- https://aave.com/design/building-glass-for-the-web
- https://github.com/samasante/liquid-glass
- https://github.com/shuding/liquid-glass
