使用网格偏移 html 锚点以调整固定标题

1 html css anchor

我试图通过固定标头获得锚点的正确位置,但它不起作用。我已经尝试过 stackoverflow 和许多其他网站提供的解决方案。我无法制定任何解决方案来正常工作。

我不知道原因是否是我使用网格和视口单位。

我的目标是了解如何仅使用 Html 和 css 使其工作,以及为什么我无法按照给出的解决方案使其工作。

你可以看到html和css:

https://codepen.io/sevaro/pen/GPLeyE

    /* css*/ 
    #container {
        display: grid;
        grid-template-columns: 1fr;
        grid-template-rows: 8vh 92vh 92vh 92vh;
        grid-template-areas: 
            "m"
            "a"
            "w"
            "c";
        }
    nav {
        grid-area: m;
        background-color: grey;
        display: flex;
        flex-flow: row;
        justify-content: flex-end;
        align-items: center;
        position: -webkit-sticky;
        position: sticky;
        top: 0;
    }    
    .about {
        grid-area: a;
        background-color: blue;
        padding-right: 10px;
    }
    .work {
        grid-area: w;
        background-color: green;
        display: flex;
        flex-flow: row wrap;
        justify-content: space-evenly;
        align-items: center;
    }
    .contact {
        grid-area: c;
        background-color: yellow;
    }
/* html */
    <div id="container">

        <nav>
            <div class="ab"><a href="#whoami">About</a></div>
            <div class="wo"><a href="#whativedone">Work</a></div>
            <div class="co"><a href="#contactme">Contact</a></div>
        </nav>


        <article class="about" id="whoami">
        </article>

        <article class="work" id="whativedone">
            <div class="project">
                <img height="50px" width="50px" alt="Project 1">
                <p>Project 1</p>
            </div>            
            <div class="project">
                <img height="50px" width="50px" alt="Project 2">
                <p>Project 2</p>
            </div>            
            <div class="project">
                <img height="50px" width="50px" alt="Project 3">
                <p>Project 3</p>
            </div>            
            <div class="project">
                <img height="50px" width="50px" alt="Project 4">
                <p>Project 4</p>
            </div>            
            <div class="project">
                <img height="50px" width="50px" alt="Project 5">
                <p>Project 5</p>
            </div>            
        </article>

        <article class="contact" id="contactme">
        </article>
Run Code Online (Sandbox Code Playgroud)

我真的很感谢任何帮助。

谢谢

我已经尝试过这些:http ://nicolasgallagher.com/jump-links-and-viewport-positioning/demo/

这些也是:https://www.wikitechy.com/technology/css-offsetting-html-anchor-adjust-fixed-header/

以及许多其他人。

dut*_*tzi 15

尝试使用scroll-margin-top,它被广泛采用。

只需将以下 CSS 添加到要滚动到的元素即可:

.element {
  scroll-margin-top: 2em;
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“scroll-margin”不会继承,因此您不能像“html {scroll-margin-top:10vh;”那样只设置一次。}`。但是,`:target {scroll-margin-top: 10vh; }` 应该可以正常工作。 (7认同)