Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anchor link screen shift position

Tags:

html

css

position

Is it possible to change the screen position when clicking an anchor link? By default when clicking an anchor link it shifts screen so that the anchor is at the very top of the screen. I would like it to shift, but I don't want to shift it all the way to top of screen, I want there to be some space from the top, maybe say 50px from the top.

Example:

<a href="#section1">section 1</a>
<a href="#section2">section 2</a>

....
....

<div id="text">
    <div id="section1">text text text</div>
    <div id="section2">text text text</div>
</div>

Thanks.

like image 250
Windbrand Avatar asked Sep 14 '25 11:09

Windbrand


1 Answers

JavaScript is not required. This will do what you want I suspect.

This solution allows you to place the anchors where you want to have the screen scroll to a position offset from the anchor specified in the CSS rule for the class adjusted-anchor.

<style>

  .anchor-container {
     position:relative;
  }

  .adjusted-anchor {
     position:absolute;
     top: -150px;
  }

</style>

<a href="#anchor">CONTINUED BELOW</a>

...


<div class="anchor-container"><div name="anchor" class="adjusted-anchor"></div></div>
<div>...continued from above</div>

The offset is fixed so if your content re-flows when the screen is resized you would have to work with percentages or JavaScript to respond to the browser resizing.

like image 96
Metauser Avatar answered Sep 17 '25 02:09

Metauser