Skip to content

Instantly share code, notes, and snippets.

@shreshthmohan
Last active August 25, 2021 05:18
Show Gist options
  • Save shreshthmohan/f25f1da435d40279e82893e8a3d36458 to your computer and use it in GitHub Desktop.
Save shreshthmohan/f25f1da435d40279e82893e8a3d36458 to your computer and use it in GitHub Desktop.
<div class="full-width" style="display: flex;">
<div class="left-chart-container" style="height: 100px; background-color: steelblue; width: 50%;"></div>
<div class="right-chart-container" style="height: 100px; background-color: steelblue; width: 50%;"></div>
</div>
<script>
function negMargin(idname) {
const de = document.getElementById(idname)
const deb = de.getBoundingClientRect()
const debw = deb.width
console.log({ debw })
const ww = window.innerWidth
if (de.style.marginLeft) {
const ml = parseFloat(de.style.marginLeft.replace('px', ''))
const unmwidth = debw + 2 * ml
const nm = `-${(ww - unmwidth - 30) / 2}px`
de.style.marginLeft = nm
de.style.marginRight = nm
} else {
const nm = `-${(ww - debw - 30) / 2}px`
de.style.marginLeft = nm
de.style.marginRight = nm
}
}
// Change this to choose a different element to make it full-width
const idOfFullWidthElement = 'full-width'
window.addEventListener('resize', function () {
negMargin(idOfFullWidthElement)
})
negMargin(idOfFullWidthElement)
</script>
function negMargin(idname) {
const de = document.getElementById(idname)
const deb = de.getBoundingClientRect()
const debw = deb.width
console.log({ debw })
const ww = window.innerWidth
if (de.style.marginLeft) {
const ml = parseFloat(de.style.marginLeft.replace('px', ''))
const unmwidth = debw + 2 * ml
const nm = `-${(ww - unmwidth - 30) / 2}px`
de.style.marginLeft = nm
de.style.marginRight = nm
} else {
const nm = `-${(ww - debw - 30) / 2}px`
de.style.marginLeft = nm
de.style.marginRight = nm
}
}
window.addEventListener('resize', function () {
negMargin('full-width')
})
negMargin('full-width')
@shreshthmohan
Copy link
Author

This small script lets a div take up (almost) the full width even when its parent isn't full width. Currently support div with a specific id (can add support for classes too)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment