粘性标题输入在输入时滚动

Nic*_*ick 8 html css

我有一个带有搜索输入的粘性标题。为确保锚标记 ( <a href='#section'>) 不会隐藏标题顶部后面的内容,我添加了以下 CSS。

html {
    scroll-padding-top: 48px
}
Run Code Online (Sandbox Code Playgroud)

但是,如果粘性标题包含输入,则当用户输入输入时整个页面将滚动。

有没有办法保留当前的滚动填充行为并防止在使用输入时自动滚动?最好只使用 HTML 和 CSS。

html {
  scroll-padding-top: 48px;
}

body {
  margin: 0;
}

header {
  position: sticky;
  top: 0;
  background: #eeeeee;
  padding: 8px 16px;
}

main {
  padding: 8px 16px;
}

main article,
main div {
  padding: 32px 0;
  border-bottom: 1px solid lightgray;
}

main div {
  background: #ddddff;
}
Run Code Online (Sandbox Code Playgroud)
<html>

<body>
  <header>
    <input type='text' placeholder='type here, page scrolls' />
  </header>
  <main>
    <article>
      <p><a href='#anchor-point'>click me to skip down to the lower section</a></p>
    </article>
    <article>
      <p>some useless text just to fill up vertical space and allow for scrolling</p>
    </article>
    <article>
      <p>some useless text just to fill up vertical space and allow for scrolling</p>
    </article>
    <div id='anchor-point'>
      I also want to link to here. This section should not get cut off by the sticky header. The entire thing should be visible.
    </div>
    <article>
      <p>some useless text just to fill up vertical space and allow for scrolling</p>
    </article>
    <article>
      <p>some useless text just to fill up vertical space and allow for scrolling</p>
    </article>
    <article>
      <p>some useless text just to fill up vertical space and allow for scrolling</p>
    </article>
  </main>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

相关帖子

在 Chrome 中编辑粘性输入元素会导致页面滚动到顶部——解决方案使用 JS 来拦截输入。如果可能的话,我宁愿在这种情况下不使用 JS。此外,该帖子中描述的原始错误似乎已修复。

las*_*2d2 4

这可能不是一个完整的答案,因为它没有回答“为什么?”的问题。

scroll-padding-top: 48px但是,如果您从 html 样式中删除,并scroll-margin-top添加目标锚点,您将获得预期的结果。

#anchor-point{
 scroll-margin-top: 48px;
}
Run Code Online (Sandbox Code Playgroud)

也可以使用:target伪类选择器来避免使用 id 选择器

:target {
 scroll-margin-top: 48px;
}
Run Code Online (Sandbox Code Playgroud)