Last active
August 13, 2021 20:19
-
-
Save jacobmc/ef492f658fd564b2420c2d3aadef501d to your computer and use it in GitHub Desktop.
Fix for using anchor links with a fixed header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Use by adding the .anchor-link class to any anchor links on the page. | |
* | |
* Works by adding a span element as the first child of the anchor link element and | |
* setting it's height to the height of the header. | |
*/ | |
(function() { | |
const header = document.getElementById('header'), | |
headerHeight = header.offsetHeight, | |
anchorLinks = document.querySelectorAll('.anchor-link'), | |
span = document.createElement('span'); | |
anchorLinks.forEach(el => { | |
el.insertBefore(span, el.firstChild); | |
let elSpan = el.querySelector('span'), | |
elPaddingTop = window.getComputedStyle(el, null).getPropertyValue('padding-top'), | |
elPaddingLeft = window.getComputedStyle(el, null).getPropertyValue('padding-left'), | |
elPaddingRight = window.getComputedStyle(el, null).getPropertyValue('padding-right'); | |
// Set the span to cover element with page background and have fixed header height | |
elSpan.style.display = 'block'; | |
elSpan.style.width = 'calc(100% + ' + elPaddingLeft + ' + ' + elPaddingRight + ')'; | |
elSpan.style.height = headerHeight + 'px'; | |
elSpan.style.background = '#d7d7d7'; // Page's background color | |
elSpan.style.marginTop = '-' + elPaddingTop; | |
elSpan.style.marginBottom = elPaddingTop; | |
elSpan.style.marginLeft = '-' + elPaddingLeft; | |
elSpan.style.marginRight = '-' + elPaddingRight; | |
// Correctly position anchor link element | |
el.style.marginTop = '-' + headerHeight + 'px'; | |
}) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment