萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

CSS 自訂捲軸樣式:WebKit 偽元素完整實作範例

現代瀏覽器(Chrome、Edge、Safari、Opera)支援透過 ::-webkit-scrollbar 系列偽元素完整客製化捲軸外觀。本文提供可直接套用的極簡深色捲軸 CSS。

完整 CSS 程式碼

/* 整體捲軸寬高 */
::-webkit-scrollbar { width: 12px; height: 12px; }

/* 軌道 */
::-webkit-scrollbar-track {
  background: #1e1e1e;
  border-radius: 10px;
  box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
}

/* 滑塊 */
::-webkit-scrollbar-thumb {
  background: rgba(0,0,0,0.1);
  border-radius: 10px;
  border: 3px solid #1e1e1e;
  box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
}
::-webkit-scrollbar-thumb:hover { background: rgba(0,0,0,0.3); }
::-webkit-scrollbar-thumb:active { background: rgba(0,0,0,0.5); }

/* 非作用中視窗 */
::-webkit-scrollbar-thumb:window-inactive { background: rgba(255,0,0,0.4); }

/* 角落 */
::-webkit-scrollbar-corner { background: #1e1e1e; }

/* 縱向/橫向專屬 */
::-webkit-scrollbar:vertical { width: 12px; }
::-webkit-scrollbar:horizontal { height: 12px; }

Firefox 標準化支援

* {
  scrollbar-width: thin;          /* auto | thin | none */
  scrollbar-color: #444 #1e1e1e;  /* thumb track */
}

局部捲軸樣式

僅針對特定容器:

.custom-scroll::-webkit-scrollbar { width: 8px; }
.custom-scroll::-webkit-scrollbar-track { background: #f1f1f1; }
.custom-scroll::-webkit-scrollbar-thumb { background: #888; border-radius: 4px; }
.custom-scroll::-webkit-scrollbar-thumb:hover { background: #555; }
<div class="custom-scroll" style="overflow:auto; max-height:300px;">...長內容...</div>

注意事項

  • WebKit 偽元素**非 W3C 標準**,未來可能變更,但短期內主流瀏覽器持續支援
  • 過度客製化可能影響使用者習慣與無障礙,建議保持原生互動行為(拖曳、滾輪、鍵盤)
  • 隱藏捲軸但保留捲動:scrollbar-width: none; -ms-overflow-style: none; + ::-webkit-scrollbar { display: none; }
copyright © 萬盛學電腦網 all rights reserved