Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to a position above a target section using in-page HTML links

I know how to jump to a section on a page using:

<a href="#link">Link</a>`
<a name="Link">

My question is: how can I make the jump location be 50px up from the default?

Basically make it so when I jump to the section, it doesn't appear exactly at the top of the browser, but allows for some buffer room.

like image 420
user3293257 Avatar asked Feb 14 '23 17:02

user3293257


2 Answers

You could add padding-top: 50px; to your target(s), with a possible unintended side-effect of always having 50px of space above your target(s).

Example:

HTML:

<a href="#test">Test</a>
<div style="height:1000px"><!-- create some whitespace for demo purposes --></div>

<h1 id="test">Target</h1>
<div style="height:1000px"><!-- create some whitespace for demo purposes --></div>

CSS:

#test { padding-top: 50px; }

DEMO

like image 156
André Dion Avatar answered Feb 17 '23 01:02

André Dion


For clean code that solves your problem, use CSS "before":

<style>
#link:before{
padding-top:50px;display:block;content:"";
}
</style>

<a href="#link">Link</a>
<div id="link">content</div>
like image 24
RanSch Avatar answered Feb 17 '23 02:02

RanSch