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

使用scrollbar-gutter:stable时Chrome屏幕宽度计算异常问题

问题原因与修复方案

问题本质

这是Chrome浏览器对scrollbar-gutter: stable与固定定位(position: fixed)元素的布局计算bug:当html层级设置scrollbar-gutter: stable后,同时设置left: 0; right: 0的固定容器,在首次渲染后的交互触发重排(比如点击)时,浏览器会错误地忽略滚动槽宽度,将视口全屏宽度作为容器宽度返回,导致元素定位偏移、被滚动条遮挡。

修复方案

方案1:将scrollbar-gutter移至body层级

把滚动槽的设置从html转移到body,同时确保html的溢出属性正确,避免布局计算冲突:

html {
  overflow-x: hidden; /* 避免横向滚动 */
}
body {
  scrollbar-gutter: stable;
  margin: 0; /* 清除默认边距 */
}
.container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: skyblue;
}
/* 其他样式保持不变 */

方案2:显式控制固定容器的宽度计算

避免同时使用left:0和right:0,改用width: 100%配合box-sizing: border-box,确保容器宽度正确包含滚动槽的扣除:

html {
  scrollbar-gutter: stable;
}
.container {
  position: fixed;
  top: 0;
  bottom: 0;
  width: 100%;
  box-sizing: border-box;
  background: skyblue;
}
/* 其他样式保持不变 */

方案3:强制容器宽度匹配视口可用宽度

通过CSS变量预定义滚动条宽度,直接计算容器可用宽度:

html {
  scrollbar-gutter: stable;
  --scrollbar-width: 17px; /* Chrome默认滚动条宽度 */
}
.container {
  position: fixed;
  top: 0;
  left: 0;
  width: calc(100vw - var(--scrollbar-width));
  bottom: 0;
  background: skyblue;
}

修改后的完整代码示例

<div class="container">
  <div class="test1"></div>
  <div class="test2">Some text example</div>
</div>

<style>
html {
  overflow-x: hidden;
}
body {
  scrollbar-gutter: stable;
  margin: 0;
}
.container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: skyblue;
}
.test1 {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 10rem;
  height: 10rem;
  background: salmon;
}
.test2 {
  position: fixed;
  right: 0;
  top: 0;
  height: 50%;
  width: 4.5rem;
  background: yellow;
}
</style>

<script>
const test = document.querySelector(".container");
document.addEventListener("click", () => console.log(test.clientWidth))
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:23:16