How to scroll to a position above a target section using in-page HTML links
18,769
Solution 1
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; }
Solution 2
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>
Solution 3
I have found this solution to be the most effective as it allows for you to add some padding above your target section, without adding spacing between your elements.
Add an invisible <div>
above your element, then move it upwards by adjusting the relative position.
<style>
#section{
position: relative;
left: 0px;
top: -90px; /* Adjust this */
}
</style>
<div id="#section"></div>
<div>content</div>
Author by
user3293257
Updated on June 14, 2022Comments
-
user3293257 almost 2 years
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.
-
user3293257 about 10 yearsactually I lied a little. The code you provided does work, although it makes the element a block and therefore provides the 50px padding on both the top and the bottom. Is there a way to make it so the padding only appears on the top ?
-
user3293257 about 10 yearshopefully you get the notification.
-
RanSch about 10 yearsI wrote "padding-top", so it should work...try with display:inline-block; I may work. If it's fine, mark the answer so users will know that it works...
-
user3293257 about 10 yearsI have tried both the suggestions you made, plus just about every property for display and padding. I have even tried to manually set the padding with -- padding: 50px 0px 0px 0px; Yet the problem still remains. Any other suggestions ?