Skip to content

Instantly share code, notes, and snippets.

@mortezasabihi
Last active April 25, 2024 11:40
Show Gist options
  • Save mortezasabihi/da421d9634342c530904f458105bc22c to your computer and use it in GitHub Desktop.
Save mortezasabihi/da421d9634342c530904f458105bc22c to your computer and use it in GitHub Desktop.
Javascript get element width without padding
const wrapper = document.querySelector('#wrapper')
const wrapperComputedStyle = window.getComputedStyle(wrapper, null)
let wrapperWidth = wrapper.clientWidth
wrapperWidth -=
parseFloat(wrapperComputedStyle.paddingLeft) +
parseFloat(wrapperComputedStyle.paddingRight)
@aderchox
Copy link

Thanks. As a function:

function getContentWidth(element) {
  let widthWithPaddings = element.clientWidth;
  const elementComputedStyle = window.getComputedStyle(element, null);
  return (
    widthWithPaddings -
    parseFloat(elementComputedStyle.paddingLeft) -
    parseFloat(elementComputedStyle.paddingRight)
  );
}

@mortezasabihi
Copy link
Author

@aderchox Thanks 🙏

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