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

Cách tạo nút thông báo (notification button) với badge số lượng bằng CSS

Giới thiệu

Notification button (nút thông báo) thường có một badge (huy hiệu) hình tròn đỏ hiển thị số lượng tin nhắn chưa đọc, góc trên phải nút. CSS dùng position: absolute để đặt badge lên góc nút.

Ví dụ hoàn chỉnh

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Notification Button</title>
  <style>
    .notif-btn {
      position: relative;
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 12px 20px;
      font-size: 16px;
      font-weight: 600;
      color: #333;
      background: #feffab;
      border: 2px solid #000;
      border-radius: 6px;
      text-decoration: none;
      transition: all 0.25s ease;
    }
    .notif-btn:hover {
      background: #2b088a;
      color: #fff;
      border-color: #2b088a;
    }
    .notif-badge {
      position: absolute;
      top: -8px;
      right: -8px;
      min-width: 22px;
      height: 22px;
      padding: 0 6px;
      font-size: 12px;
      font-weight: 700;
      line-height: 22px;
      color: #fff;
      background: #00aa33;
      border-radius: 999px; /* pill shape */
      text-align: center;
      box-shadow: 0 0 0 2px #fff; /* viền trắng tách khỏi nút */
    }
    .notif-badge.zero { display: none; } /* Ẩn khi 0 */
  </style>
</head>
<body>
  <h1 style="text-align:center; margin:40px 0">Notification Button</h1>
  <div style="text-align:center">
    <a href="#" class="notif-btn">
      <span>Tin nhắn</span>
      <span class="notif-badge">99+</span>
    </a>
    <br><br>
    <a href="#" class="notif-btn">
      <span>Thông báo</span>
      <span class="notif-badge zero">0</span>
    </a>
  </div>
</body>
</html>

Chi tiết kỹ thuật Badge

  • position: absolute + top/right âm: Đẩy badge ra ngoài góc nút.
  • min-width + border-radius: 999px: Hình tròn cho 1 chữ số, hình pill cho 2+ chữ số.
  • box-shadow: 0 0 0 2px #fff: Tạo viền trắng "cắt" badge ra khỏi nền nút, dễ nhìn hơn.
  • line-height = height: Căn giữa chữ theo chiều dọc.

Các biến thể Badge

Badge chấm đơn giản (chỉ báo có thông báo, không hiện số)

.dot-badge {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 10px;
  height: 10px;
  background: #f44336;
  border-radius: 50%;
  border: 2px solid #fff;
}

Badge với animation pulse (nhấp nháy)

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.15); }
}
.notif-badge.pulse { animation: pulse 1.5s ease-in-out infinite; }

Nâng cấp: Cập nhật số lượng real-time (JavaScript)

function updateBadge(count) {
  const badge = document.querySelector('.notif-badge');
  if (count > 0) {
    badge.textContent = count > 99 ? '99+' : count;
    badge.classList.remove('zero');
  } else {
    badge.classList.add('zero');
  }
}
// Ví dụ: updateBadge(5); updateBadge(0);