You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Safari浏览器中实现scrollbar-gutter: stable效果?

解决 Safari 不支持 scrollbar-gutter 导致的右侧间距不对称问题

你的问题核心是 Safari 不支持 scrollbar-gutter: stable,导致滚动条出现时会挤压内容,破坏原本的右侧间距布局。下面提供两种实用兼容方案:

方案一:CSS 特性检测精准兼容

通过 @supports 区分支持 scrollbar-gutter 的浏览器和 Safari,给 Safari 单独预留滚动条空间:

修改后的完整 CSS 代码:

.card {
  background: red;
  padding: 24px 12px 24px 24px;
  width: 240px;
  margin: 0 auto;
  height: 160px;
}

.scrollable-content {
  scrollbar-gutter: stable;
  overflow-y: auto;
  scrollbar-width: thin;
  /* 给 Safari 预留滚动条宽度的空间 */
  padding-right: 12px;
}

/* 对支持 scrollbar-gutter 的浏览器,移除额外的右侧内边距 */
@supports (scrollbar-gutter: stable) {
  .scrollable-content {
    padding-right: 0;
  }
}

.scrollable-content::-webkit-scrollbar {
  width: 12px;
  background-color: blue;
}

.scrollable-content::-webkit-scrollbar-track {
  border-radius: 8px;
}

.scrollable-content::-webkit-scrollbar-thumb {
  background-clip: content-box;
  background-color: rgba(136, 136, 136, 0.5);
  border: 4px solid transparent;
  border-radius: 8px;
  height: 56px;
}

.scrollable-content::-webkit-scrollbar-thumb:hover {
  background-color: #888888;
}

.card-body {
  background-color: yellow;
}

方案二:嵌套容器模拟滚动条预留空间

通过两层容器分离布局空间和滚动区域,确保无论滚动条是否出现,外层容器的宽度始终稳定:

修改后的 HTML:

<div class="card">
  <div class="scrollable-container">
    <div class="scrollable-content">
      <div class="card-body">
        test lorem100
      </div>
    </div>
  </div>
</div>

修改后的完整 CSS 代码:

.card {
  background: red;
  padding: 24px 12px 24px 24px;
  width: 240px;
  margin: 0 auto;
  height: 160px;
}

/* 外层容器隐藏溢出,固定布局宽度 */
.scrollable-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

/* 内层容器宽度比外层宽出滚动条宽度,负责承载滚动逻辑 */
.scrollable-content {
  width: calc(100% + 12px);
  height: 100%;
  overflow-y: auto;
  scrollbar-width: thin;
}

.scrollable-content::-webkit-scrollbar {
  width: 12px;
  background-color: blue;
}

.scrollable-content::-webkit-scrollbar-track {
  border-radius: 8px;
}

.scrollable-content::-webkit-scrollbar-thumb {
  background-clip: content-box;
  background-color: rgba(136, 136, 136, 0.5);
  border: 4px solid transparent;
  border-radius: 8px;
  height: 56px;
}

.scrollable-content::-webkit-scrollbar-thumb:hover {
  background-color: #888888;
}

.card-body {
  background-color: yellow;
}

两种方案各有优势:

  • 方案一更简洁,利用原生 CSS 特性检测做精准兼容;
  • 方案二更通用,不依赖浏览器特性支持,适配更复杂的布局场景。

内容的提问来源于stack exchange,提问作者yourBadApple

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 21:12:30