为页面内的链接添加边距
页面内的链接将您的内容滚动到浏览器窗口的顶部。有什么办法可以增加保证金吗?我将使用一些 JavaScript 来引导滚动,但希望有一个可行的后备方案。
简而言之,我可以在 CSS 中添加边距,以便在浏览器窗口顶部和页面链接部分之间添加一些空间吗?
HTML:
<nav>
<a href="#test">TEST</a>
</nav>
<div class="section">
<a name="test"></a>
<p>This content should be offset from the top of the page when scrolled to</p>
</div>
Links within a page scroll your content to the top of the browser window. Is there any way to add a margin to that? I'll be using some javascript to guide the scrolling, but would like to have a viable fallback.
So, in short, can I add a margin in CSS that will add some space inbetween the top of the browser window and a section when it's a page link.
HTML:
<nav>
<a href="#test">TEST</a>
</nav>
<div class="section">
<a name="test"></a>
<p>This content should be offset from the top of the page when scrolled to</p>
</div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
CSS 现在支持
scroll-margin-top
。
这是 2021 年最好的方法。
CSS now supports
scroll-margin-top
.This is the best way to do it in 2021.
进行页内链接的首选方法是使用 id 而不是 name 属性。
应该匹配:
从这里您可以轻松地将填充添加到 #test div 的顶部,这将是您的滚动位置。
示例:http://tinkerbin.com/EvV7byy9
the preferred way to do in-page links is to use the id instead of name attribute.
should match up with:
From here you can easily add padding to the top of the #test div and that will be your scroll position.
Example: http://tinkerbin.com/EvV7byy9
嗯,我会将每个部分中的锚点设置为绝对定位,距该部分的开头大约 10px。它看起来像这样:
这本质上是 10 像素的边距。您可以相应地调整 top 的值来更改边距/填充。我还使用了直接后代运算符 ( > ),因此段落中的链接不会受到影响。
另外,正如 @NathanManousos 所提到的,您不应再使用 name 属性,而应使用 ID 属性。相对文档链接将滚动到任何元素的 ID,而不仅仅是链接。您可以在每个部分 DIV 上放置一个 ID,并使用填充滚动到 div 的顶部,填充将导致实际内容在 div 中进一步向下。
Hmm, I would set the anchors in each section to be positioned absolutely, about 10px down from the start of the section. It would look like this:
That is essentially a 10 pixel margin. You can adjust the value of top accordingly to change the margin/padding. I also used the direct descendant operator ( > ) so links in the paragraphs won't be affected.
Also, as mentioned by @NathanManousos, you should no longer use the name attribute, but the ID attribute. Relative document links will scroll to the ID of any element, not just links. You could put an ID on each of your section DIVs and use padding to scroll to the top of the div, and the padding will cause the actual content to be further down in the div.
解决方案是
scroll-margin-top
。这允许您指定任何单位的偏移量,为您滚动到的部分提供“空间”请参阅 ARA Münsterlingen | 的实时示例安拉根
The solution is
scroll-margin-top
. This allows you to specify an offset in any units you like to give "head room" to the section you are scrolling toSee a live example at ARA Münsterlingen | Anlagen