Is the landing location of a URI Fragment variable? Or is it always top?

Viewed 54

So, when you with link internally on the page with eg. <a href="#fragment"> to <div id="fragment">, and click it, it places the target always at the very top of the viewport(as far as the scrollbar will go that is.)

Is there a way to address/modify that location to, for example, the absolute center of your viewport?

1 Answers

You can add a margin using the scroll-margin property. Add scroll-margin to the target element. (here #fragment).

Example:

#fragment {
    margin: 1000px 0; /*Just to make the page scrollable*/
    scroll-margin: 50vh;
}
<a href="#fragment">Click Me</a>

<div id="fragment">
  Lorem ipsum dolor sit, amet consectetur adipisicing elit. Pariatur maxime, accusantium eius in iusto accusamus rerum dignissimos vero minima minus doloribus inventore ipsam distinctio, natus aut velit autem dolorem reprehenderit.
</div>


Explanation:

Here scroll-margin: 50vh;, 50vh will make the element #fragment appear on 50% of the current viewport height when clicked on the link.


Codepen

Related