如何让Div滚动条仅在鼠标悬停时显示?适配MacOS 10.15
实现MacOS 10.15+上Div仅鼠标悬停时显示滚动条
我有如下Div元素:
<div style='overflow:auto; width:50px;height:50px;'>here is some text</div>,因文本过长,滚动条处于显示状态。但在Mac系统上存在两种表现:MacOS 10.15中滚动条始终可见;低于10.15的版本中,仅当鼠标悬停在Div上时滚动条才显示,移出后隐藏,视觉体验更舒适。该差异在Safari、Firefox、Chrome、Opera等所有浏览器中均存在。请问如何实现即使在MacOS 10.15上,也仅在鼠标悬停Div时显示滚动条?
刚好之前碰到过类似的需求,给你整理了一套兼容所有主流浏览器的CSS方案,能实现不管MacOS版本如何,都只在鼠标悬停div时显示滚动条的效果:
核心思路
通过自定义滚动条样式,默认隐藏滚动条,当鼠标悬停在目标div上时再显示,同时兼顾webkit内核(Chrome、Safari、Opera)和Firefox的差异。
完整代码实现
CSS部分
/* 给目标div添加类名,便于样式控制 */ .custom-scrollbar { overflow: auto; width: 50px; height: 50px; } /* --- 针对webkit内核浏览器(Chrome、Safari、Opera) --- */ /* 默认状态下隐藏滚动条 */ .custom-scrollbar::-webkit-scrollbar { width: 0; /* 把宽度设为0,完全隐藏 */ height: 0; } /* 鼠标悬停时显示滚动条,并设置宽度 */ .custom-scrollbar:hover::-webkit-scrollbar { width: 8px; /* 可根据需求调整宽度 */ height: 8px; } /* 自定义滚动条轨道样式 */ .custom-scrollbar::-webkit-scrollbar-track { background-color: #f1f1f1; border-radius: 4px; /* 圆角处理,更贴合Mac风格 */ } /* 自定义滚动条滑块样式 */ .custom-scrollbar::-webkit-scrollbar-thumb { background-color: #888; border-radius: 4px; } /* 鼠标悬停在滑块上时加深颜色 */ .custom-scrollbar::-webkit-scrollbar-thumb:hover { background-color: #555; } /* --- 针对Firefox浏览器 --- */ /* 默认状态下隐藏滚动条 */ .custom-scrollbar { scrollbar-width: none; } /* 鼠标悬停时显示细滚动条 */ .custom-scrollbar:hover { scrollbar-width: thin; } /* 设置Firefox滚动条的滑块和轨道颜色 */ .custom-scrollbar:hover { scrollbar-color: #888 #f1f1f1; }
HTML部分
<div class="custom-scrollbar">here is some text that's long enough to trigger the vertical scrollbar, let's add more content to make sure it works properly</div>
效果说明
- 在MacOS 10.15+及更低版本上,目标div默认不会显示滚动条,只有当鼠标悬停上去时才会出现,移出后自动隐藏。
- 自定义的滚动条样式更贴合视觉体验,你也可以根据自己的需求调整颜色、圆角和宽度参数。
内容的提问来源于stack exchange,提问作者dem_81
相关产品推荐
相关产品推荐

