如何使用 CSS 建立黑白影像


透過指定 CSS 的 filter 屬性的灰度值,我們可以建立一個黑白影像。filter 屬性可用於對影像應用特殊效果,如模糊、陰影等。

語法

CSS 過濾屬性的語法如下 −

Selector {
   filter: grayscale(100%);
   -webkit-filter: grayscale(100%);
}

示例

以下示例說明了 CSS 的 filter 屬性。

 線上演示

<!DOCTYPE html>
<html>
   <head>
      <style>
         img {
            margin: 2%;
            border-radius: 25%;
         }
         img:nth-of-type(even) {
            filter: grayscale(100%);
            -webkit-filter: grayscale(100%);
         }
      </style>
   </head>
   <body>
      <img src="https://images.unsplash.com/photo-1611825715408-826f2b19c43f?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=200" alt="img from unsplash">
      <img src="https://images.unsplash.com/photo-1611825715408-826f2b19c43f?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=200&ixlib=rb-1.2.1&q=80&w=200" alt="img from unsplash">
   </body>
</html>

輸出結果如下

示例

 線上演示

<!DOCTYPE html>
<html>
   <head>
      <style>
         img {
            margin: 2%;
         }
         img:nth-of-type(odd) {
            filter: grayscale(100%);
            -webkit-filter: grayscale(100%);
         }
      </style>
   </head>
   <body>
      <img src="https://images.unsplash.com/photo-1611781750917-8777ab68668a?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=256&ixlib=rb-1.2.1&q=80&w=256">
      <img src="https://images.unsplash.com/photo-1611781750917-8777ab68668a?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=256&ixlib=rb-1.2.1&q=80&w=256">
   </body>
</html>

輸出結果如下

更新於:2021 年 2 月 10 日

8k+ 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始學習
廣告