Explain Codes LogoExplain Codes Logo

Make anchor link go some pixels above where it's linked to

css
scroll-position
javascript-scrolling
css-positioning
Nikita BarsukovbyNikita Barsukov·Nov 9, 2024
TLDR

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.

.anchor::before { content: ''; display: block; margin-top: -50px; /* Adjustment distance */ padding-top: 50px; visibility: hidden; }

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:

.target { scroll-margin-top: 100px; /* Standard header height or required offset */ }

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.

// Listen to anchor clicks document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function (e) { e.preventDefault(); // No default anchor action please const targetId = this.getAttribute('href'); const targetElement = document.querySelector(targetId); // Get position and apply offset const offsetPosition = targetElement.getBoundingClientRect().top + window.pageYOffset - 50; // Gracefully scroll to the tweaked position window.scrollTo({ top: offsetPosition, behavior: "smooth" }); }); });

Recurring anchor clicks and hash changes

To tackle consecutive anchor clicks and hash changes, event listeners to the rescue:

window.addEventListener('hashchange', function() { // The genius logic to handle the scroll adjustment post hash change });

Introduce a delay with setTimeout

Sometimes, a pause could do wonders:

setTimeout( () => window.scrollTo(...), 1); // Holds the scrollTo just enough

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:

$('a[href^="#"]').on('click', function(event) { // Similar scrollTo logic but written in the much loved jQuery syntax });