將scroll bar 隱藏,但可用滑鼠滑動
有兩種主流的方法可以實現「隱藏捲軸但保留滾動功能」,一種是現代 CSS 的標準方法,另一種是傳統的 "hacky" 技巧。
方法一:現代 CSS 標準方法 (最推薦)
.scrollable-content {
/* 1. 基礎設定:確保內容可以滾動 */
overflow-y: scroll; /* 或者 auto */
height: 200px; /* 必須有一個固定的高度或最大高度 */
/* 2. 針對 Firefox */
scrollbar-width: none;
/* 3. 針對 Chrome, Safari, Edge (WebKit/Blink 核心) */
/* 使用 ::-webkit-scrollbar 偽元素 */
}
.scrollable-content::-webkit-scrollbar {
display: none; /* 直接隱藏整個捲軸 */
}
overflow-y: scroll; : 這是基礎,它告訴瀏覽器這個元素在垂直方向上是可以滾動 的。如果沒有這一行,內容即使超出也不會產生滾動效果。scrollbar-width: none; : 這是 Firefox 瀏覽器的標準屬性,直接告訴它「不要顯示捲軸」。::-webkit-scrollbar : 這是一個 CSS偽元素 ,專門用來選取 WebKit/Blink 核心瀏覽器(如 Chrome, Safari)的捲軸。display: none; : 我們選取到捲軸後,直接將它隱藏掉。
完整範例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hide Scrollbar Example</title>
<style>
.scrollable-content {
width: 300px;
height: 200px;
border: 1px solid #ccc;
padding: 15px;
/* 關鍵部分 */
overflow-y: auto;
scrollbar-width: none; /* For Firefox */
}
.scrollable-content::-webkit-scrollbar {
display: none; /* For Chrome, Safari, and Opera */
}
</style>
</head>
<body>
<div class="scrollable-content">
<p>這是一個可以滾動的容器。</p>
<p>雖然你看不到捲軸,但是你可以使用滑鼠滾輪、觸控板手勢或在觸控螢幕上滑動來滾動內容。</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
<p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>這是結尾。</p>
</div>
</body>
</html>
⚠️ 重要的無障礙 (Accessibility) 提醒
沒有滑鼠滾輪或觸控板的用戶(例如,只使用鍵盤的用戶)可能 完全不知道 這塊區域是可以滾動的。即使是普通用戶,也可能不會發現有更多內容可以查看。
在內容底部顯示一個淡淡的漸層陰影,暗示下方還有內容。 提供明確的「向上/向下」按鈕。 確保內容可以透過鍵盤的 Tab 鍵和方向鍵進行導航和滾動。
方法二:傳統 "padding/margin" 技巧
<div class="outer-container">
<div class="inner-container">
<!-- 你的大量內容放在這裡 -->
</div>
</div>
.outer-container {
height: 200px;
width: 300px;
overflow: hidden; /* 把超出部分(也就是捲軸)藏起來 */
}
.inner-container {
height: 100%;
width: 100%;
padding-right: 17px; /* 增加一個捲軸的寬度,把捲軸擠到外面 */
box-sizing: content-box; /* 確保 padding 是加在 width 外面 */
overflow-y: scroll;
}
留言
張貼留言