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

Tạo Custom Scrollbar (Thanh cuộn tùy chỉnh) với CSS

Tùy chỉnh scrollbar cho WebKit (Chrome, Edge, Safari, Opera). Firefox dùng scrollbar-width và scrollbar-color.

Ví dụ mã nguồn (WebKit)

<!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;
    height: 200vh; /* Tạo scrollbar */
  }
  ::-webkit-scrollbar {
    width: 20px; /* Chiều rộng scrollbar dọc */
    height: 20px; /* Chiều cao scrollbar ngang */
  }
  p { font-size: 40px; }
  /* Track (đường ray) */
  ::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px grey;
    border-radius: 10px;
    background: #f1f1f1;
  }
  /* Thumb (cái nút kéo) */
  ::-webkit-scrollbar-thumb {
    background: rgb(75, 22, 161);
    border-radius: 10px;
    border: 3px solid #f1f1f1; /* Tạo khoảng cách với track */
  }
  ::-webkit-scrollbar-thumb:hover {
    background: #9156ff;
  }
  /* Corner (góc scrollbar ngang/dọc) */
  ::-webkit-scrollbar-corner {
    background: #f1f1f1;
  }
</style>
</head>
<body>
<h1>Custom Scrollbar Example</h1>
<h2>Chỉ hoạt động trên WebKit (Chrome, Edge, Safari, Opera). Không hoạt động Firefox, IE.</h2>
<p>Lorem ipsum dolor sit amet...</p>
</body>
</html>

Firefox Support (CSS Scrollbars Spec)


/* Firefox 64+ */
html {
  scrollbar-width: thin; /* auto | thin | none */
  scrollbar-color: rgb(75, 22, 161) #f1f1f1; /* thumb track */
}

Cross-browser Complete


/* WebKit */
::-webkit-scrollbar { width: 12px; height: 12px; }
::-webkit-scrollbar-track { background: #f1f1f1; }
::-webkit-scrollbar-thumb { background: #888; border-radius: 6px; }
::-webkit-scrollbar-thumb:hover { background: #555; }

/* Firefox */
* { scrollbar-width: thin; scrollbar-color: #888 #f1f1f1; }

Lưu ý

  • Không thể style scrollbar trên IE (dùng -ms-overflow-style: none để ẩn)
  • Tránh làm scrollbar quá mỏng/khoá khéo trên mobile (touch scroll không dùng scrollbar)
  • Luôn đảm bảo contrast đủ cho accessibility