1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

`scroll-margin-top` Fails to Offset Anchor Scroll in Angular App

Discussão em 'Angular' iniciado por Filip Trivan, Junho 5, 2025.

  1. Filip Trivan

    Filip Trivan Guest

    I have a fixed header in my Angular application. When navigating to anchor links using #, the target element scrolls behind the header. I want to create some spacing so that the scrolled-to content appears below the header, not hidden behind it.

    I tried applying a scroll-margin-top to anchor targets to create spacing below the fixed header. Specifically, I added the following CSS:

    [id] {
    scroll-margin-top: 100px;
    }


    However, it doesn't seem to have any effect when navigating to elements via anchor links (e.g., #section1).

    I was able to solve the issue by adding the following code to app.component.ts:

    import { ViewportScroller } from "@angular/common";
    // ...

    constructor(
    private viewportScroller: ViewportScroller
    ) {
    viewportScroller.setOffset([0, 100]);
    }

    //...


    This successfully offsets the scroll position by 100px, which keeps the anchor target visible below the fixed header.

    However, I'm still curious, why didn't the previous attempt using scroll-margin-top in CSS work as expected?

    Continue reading...

Compartilhe esta Página