Created
February 9, 2021 15:57
-
-
Save celsowhite/51dda01c52e8617d1c26ddea83aef0f8 to your computer and use it in GitHub Desktop.
Calculate and set the container margin as a css variable. Helpful when breaking elements out of their container while maintaining alignment.
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
/*------------------------- | |
Calculate Container Margin | |
-------------------------*/ | |
document.addEventListener('DOMContentLoaded', event => { | |
let root = document.documentElement; | |
// Calculate Container Margin | |
function calculateContainerMargin() { | |
const container = document.querySelector('.container'); | |
// If a container is on the page then set the margin variable programmatically. | |
if (container) { | |
// Set the margin property based on the offsetLeft. The offsetLeft will always be the margin for left and right because the container is centered. | |
root.style.setProperty('--container-margin', container.offsetLeft + 'px'); | |
} | |
} | |
// On init set the margin. | |
calculateContainerMargin(); | |
// On window resize set the margin. | |
window.addEventListener('resize', calculateContainerMargin); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment