Make anchor link go some pixels above where it's linked to
To analytically offset anchor links, utilize CSS pseudo-elements. Initiate an imperceptible block before the anchor, using a negative margin and a corresponding positive padding.
Connect the .anchor
class to your target anchors. Modify the margin-top
for your specific offset needs.
Precision control with CSS
Employ scroll margin
By using scroll-margin-top
, you can work a different angle by moving the target element:
Capitalize on pseudo elements
For the old guard browsers, stick to the initial pseudo-element approach for backwards compatibility.
Handling it with JavaScript
A leash on scroll position
In case CSS can't cut it, window.scrollTo
in JavaScript assists to manually control scroll position.
Recurring anchor clicks and hash changes
To tackle consecutive anchor clicks and hash changes, event listeners to the rescue:
Introduce a delay with setTimeout
Sometimes, a pause could do wonders:
JavaScript toolbox
Absolute positioning for precision
An alternate to padding/margin shifts done in CSS:
- Encase anchor targets in a container with
position: relative
. - Assign absolute positioning to your anchors, and manipulate them using
top
.
jQuery for the modern coder
If jQuery is your language of choice:
Was this article helpful?