ปรับแต่ง Scrollbar ให้เข้ากับธีมเว็บ ด้วย WebKit Pseudo-elements
ใช้ ::-webkit-scrollbar, ::-webkit-scrollbar-track, ::-webkit-scrollbar-thumb ปรับสี ความกว้าง มุมโค้ง เหมาะสำหรับ WebKit/Blink browsers (Chrome, Edge, Safari)
โค้ดตัวอย่าง
<!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; }
p { font-size: 40px; }
::-webkit-scrollbar { width: 20px; }
::-webkit-scrollbar-track {
box-shadow: inset 0 0 5px grey; border-radius: 10px;
}
::-webkit-scrollbar-thumb {
background: rgb(75, 22, 161); border-radius: 2px;
}
::-webkit-scrollbar-thumb:hover { background: #9156ff; }
</style>
</head>
<body>
<h1>ตัวอย่าง Custom Scrollbar</h1>
<h2>ไม่ทำงานใน IE, Edge (Legacy), Firefox</h2>
<p>Lorem ipsum...</p>
</body>
</html>
โครงสร้าง Scrollbar Pseudo-elements
::-webkit-scrollbar– ทั้ง scrollbar (width/height)::-webkit-scrollbar-track– ราง (track)::-webkit-scrollbar-thumb– ขับเคลื่อน (thumb)::-webkit-scrollbar-button– ปุ่มลูกศร (เด่นๆ)::-webkit-scrollbar-corner– มุมตัดของ horizontal+vertical
Firefox Support
Firefox ใช้ scrollbar-width (auto | thin | none) และ scrollbar-color (thumb track):
.custom-scroll {
scrollbar-width: thin;
scrollbar-color: rgb(75, 22, 161) #eee;
}
Cross-browser Strategy
.custom-scroll {
/* Firefox */
scrollbar-width: thin;
scrollbar-color: #4b16a1 #eee;
}
/* WebKit */
.custom-scroll::-webkit-scrollbar { width: 12px; }
.custom-scroll::-webkit-scrollbar-track { background: #eee; }
.custom-scroll::-webkit-scrollbar-thumb { background: #4b16a1; border-radius: 6px; }
.custom-scroll::-webkit-scrollbar-thumb:hover { background: #9156ff; }
ใช้ทั้งคู่พร้อมกันได้ – Browser จะเลือกที่รองรับ