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

Tạo văn bản cắt lỗ (knockout text) responsive với CSS


Kỹ thuật knockout text (văn bản cắt lỗ) cho phép hiển thị hình ảnh nền qua các chữ cái, tạo hiệu ứng chữ "đục lỗ" rất đẹp mắt. Dưới đây là cách thực hiện responsive:

Ví dụ

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body {font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}
    .image-container {
      background-image: url("https://images.pexels.com/photos/957024/forest-trees-perspective-bright-957024.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940");
      background-size: cover;
      position: relative;
      height: 300px;
    }
    .text {
      background-color: rgb(0, 0, 0);
      color: rgb(255, 255, 255);
      font-size: 10vw;
      font-weight: bold;
      margin: 0 auto;
      padding: 10px;
      width: 50%;
      text-align: center;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      mix-blend-mode: multiply;
    }
  </style>
</head>
<body>
  <h1 style="text-align: center;">Ví dụ Văn Bản Cắt Lỗ Responsive</h1>
  <div class="image-container">
    <div class="text">FOREST</div>
  </div>
</body>
</html>

Kết quả

Chữ "FOREST" màu trắng trên nền đen, nhưng nhờ mix-blend-mode: multiply, nền đen trở nên trong suốt và hiển thị hình ảnh rừng qua các chữ cái.

Giải thích quan trọng

  • mix-blend-mode: multiply là thuộc tính then chốt - nó làm cho màu đen trở nên trong suốt
  • font-size: 10vw làm chữ tự động co giãn theo chiều rộng viewport
  • Cần đặt background-color cho chữ (ở đây là đen) để blend mode hoạt động