overflow-anchor

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

overflow-anchor CSS 属性提供了一种选择退出浏览器滚动锚定行为的方法,该行为会调整滚动位置以最大程度地减少内容偏移。

在任何支持滚动锚定的浏览器中,滚动锚定行为默认启用。因此,通常只有在文档或文档的某个部分出现滚动锚定问题并需要关闭此行为时,才需要更改此属性的值。

试一试

overflow-anchor: auto;
overflow-anchor: none;
<section class="default-example" id="default-example">
  <div class="whole-content-wrapper">
    <button id="playback" type="button">Start lottery</button>
    <p>Magic numbers for today are:</p>
    <div id="example-element"></div>
  </div>
</section>
.whole-content-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

#example-element {
  height: 100%;
  border: 2px dashed dodgerblue;
  padding: 0.75em;
  text-align: left;
  overflow: scroll;
}

#playback {
  font-size: 1em;
  width: 10em;
  height: 4em;
  font-weight: bold;
  margin: 1em auto;
  background-color: aliceblue;
  border: solid 2px dodgerblue;
  border-radius: 5px;
}

#playback:hover {
  border-color: lightseagreen;
}

#playback:active {
  filter: brightness(0.9);
}
const example = document.getElementById("example-element");
const button = document.getElementById("playback");
let intervalId;

function setInitialState() {
  example.innerHTML = "";
  Array.from({ length: 10 }, (_, i) => i).forEach(addContent);
  example.scrollTop = example.scrollHeight;
}

function addContent() {
  console.log("adding content");
  const magicNumber = Math.floor(Math.random() * 10000);
  example.insertAdjacentHTML(
    "afterbegin",
    `<div class="new-content-container">New Magic Number: ${magicNumber}</div>`,
  );
}

button.addEventListener("click", () => {
  if (example.classList.contains("running")) {
    example.classList.remove("running");
    button.textContent = "Start lottery";
    clearInterval(intervalId);
  } else {
    example.classList.add("running");
    button.textContent = "Stop lottery";
    setInitialState();
    intervalId = setInterval(addContent, 1000);
  }
});

语法

css
/* Keyword values */
overflow-anchor: auto;
overflow-anchor: none;

/* Global values */
overflow-anchor: inherit;
overflow-anchor: initial;
overflow-anchor: revert;
overflow-anchor: revert-layer;
overflow-anchor: unset;

auto

调整滚动位置时,此元素成为一个潜在的锚点。

none

此元素不会被选作潜在的锚点。

正式定义

初始值auto
应用于所有元素
继承性
计算值同指定值
动画类型离散

正式语法

overflow-anchor = 
auto |
none

示例

防止滚动锚定

要防止文档中的滚动锚定,请使用 overflow-anchor 属性。

css
* {
  overflow-anchor: none;
}

规范

规范
CSS 滚动锚定模块级别 1
# 排除 API

浏览器兼容性

另见