Skip to content

Instantly share code, notes, and snippets.

@celsowhite
Created February 9, 2021 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celsowhite/51dda01c52e8617d1c26ddea83aef0f8 to your computer and use it in GitHub Desktop.
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.
/*-------------------------
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