在页面内链接添加保证金

tec*_*ant 4 html css anchor scroll margin

页面中的链接将您的内容滚动到浏览器窗口的顶部.有没有办法为此添加保证金?我将使用一些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>
Run Code Online (Sandbox Code Playgroud)

dch*_*cke 6

CSS 现在支持scroll-margin-top.

这是 2021 年最好的方法。


Nat*_*sos 5

进行页内链接的首选方法是使用id而不是name属性.

<a href="#test">
Run Code Online (Sandbox Code Playgroud)

应符合:

<div id="test">
Run Code Online (Sandbox Code Playgroud)

从这里你可以轻松地将填充添加到#test div的顶部,这将是你的滚动位置.

示例:http://tinkerbin.com/EvV7byy9