Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Tạo ảnh đen trắng (black & white) với CSS filter


Sử dụng filter: grayscale(100%) để chuyển ảnh sang đen trắng. Có thể kết hợp với hover để hiệu ứng màu ↔ đen trắng.

Cú pháp

selector {
  filter: grayscale(100%);
  -webkit-filter: grayscale(100%); /* Safari cũ */
}

Ví dụ 1: Xen kẽ màu/đen trắng

<!DOCTYPE html>
<html>
<head>
  <style>
    img {
      margin: 2%;
      border-radius: 25%;
      width: 200px;
      height: 200px;
      object-fit: cover;
      transition: filter 0.3s ease;
    }
    img:nth-of-type(even) {
      filter: grayscale(100%);
      -webkit-filter: grayscale(100%);
    }
    img:hover {
      filter: grayscale(0%);
    }
  </style>
</head>
<body>
  <img src="https://images.unsplash.com/photo-1611825715408-826f2b19c43f?w=200&h=200&fit=crop" alt="Ảnh 1">
  <img src="https://images.unsplash.com/photo-1611825715408-826f2b19c43f?w=200&h=200&fit=crop" alt="Ảnh 2 (đỏ trắng)">
</body>
</html>

Ví dụ 2: Hover chuyển màu

<style>
  .gallery img {
    width: 250px;
    height: 250px;
    object-fit: cover;
    border-radius: 12px;
    filter: grayscale(100%);
    transition: filter 0.4s ease, transform 0.4s ease;
  }
  .gallery img:hover {
    filter: grayscale(0%);
    transform: scale(1.02);
  }
</style>
<div class="gallery">
  <img src="..." alt="...">
  <img src="..." alt="...">
</div>

Kết quả

Ảnh ban đầu đen trắng, hover chuột vào chuyển sang màu gốc mượt mà, có thể kèm zoom nhẹ.

Các filter khác

  • blur(5px) - làm mờ
  • sepia(100%) - màu nâu cũ
  • brightness(150%) - tăng độ sáng
  • contrast(200%) - tăng độ tương phản
  • hue-rotate(90deg) - xoay màu
  • Kết hợp: filter: grayscale(50%) blur(2px);