如何使用 CSS 创建黑白图像

cssweb developmentfront end technology更新于 2024/5/16 10:52:17

通过为 CSS 的 filter 属性指定灰度值,我们可以创建黑白图像。filter 属性可用于对图像应用模糊、阴影等特殊效果。

语法

CSS filter 属性的语法如下 −

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>

这将给出以下输出


相关文章


有用资源