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

将CSS Grid首个元素移至下一行致页面滚动,是否为预期行为?

CSS Grid 元素移动导致页面自动滚动:预期行为还是Bug?

这不是CSS Grid的Bug,而是浏览器**滚动锚定(Scroll Anchoring)**机制带来的预期行为。

原因解释

滚动锚定是浏览器为优化用户体验设计的功能:当页面布局发生变化(比如元素位置移动、尺寸改动)时,浏览器会自动调整滚动位置,避免用户正在查看的内容突然移出视野。

你的场景里,第一个网格项.item-1是页面中较早出现的可见元素,被浏览器识别为滚动锚点。当你用grid-area把它移到下一行时,这个锚点元素的位置向下偏移,浏览器为了维持锚点的可见性,就会自动向下滚动页面。而第二个网格项不是浏览器优先选择的锚点候选,所以移动它不会触发滚动调整。

验证与解决

你可以通过禁用滚动锚定来验证这个机制:在.grid容器或<body>上添加CSS属性:

overflow-anchor: none;

此时再移动第一个网格项,页面就不会自动滚动了。

相关资源

  • CSS滚动锚定官方规范:CSS Scroll Anchoring Module Level 1
  • 浏览器实现逻辑:滚动锚定默认启用,会跟踪页面中稳定的可见元素作为锚点,当布局变化时自动调整滚动位置以保持锚点在视野内。

复现代码

HTML

<html>
<body>
  <h2>
    Scroll down until the grid items are half hidden, then press the buttons to see the behavior
  </h2>
  <h3>Refresh between button presses</h3>
  <div class="big-box"></div>

  <div class="grid">
    <div class="item-1">
      shtshtsh
    </div>
    <div class="item-2">
      shtshths
    </div>
    <div class="item-3"></div>
    <div class="item-4"></div>
  </div>

  <button class="button-1">
      Move first grid item and see the scroll bar move
    </button>
  <button class="button-2">
      Move second grid item, and it behaves correctly
    </button>

  <div class="big-box"></div>
</body>
</html>

CSS

body {
  font-family: sans-serif;
}

.big-box {
  width: 100%;
  height: 500px;
}

.grid {
  grid-template-columns: repeat(4, minmax(100px, 1fr));
  grid-template-rows: repeat(3, minmax(100px, 1fr));
  gap: 12px;
  display: grid;
  width: 100%;
  background: #f1f1f1;
  /* 取消注释可禁用滚动锚定 */
  /* overflow-anchor: none; */
}

.item-1 {
  background-color: #2eb5daff;
}

.item-2 {
  background-color: #387e48;
}

.item-3 {
  background-color: #c32eda;
}

.item-4 {
  background-color: #dac32e;
}

JavaScript

document.querySelector(".button-1").addEventListener("click", () => {
  document.querySelector(".item-1").style.gridArea = "2/2/2/1";
});

document.querySelector(".button-2").addEventListener("click", () => {
  document.querySelector(".item-2").style.gridArea = "2/2/3/3";
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:27:37