Skip to content

Instantly share code, notes, and snippets.

@livemehere
Last active March 24, 2024 08:43
Show Gist options
  • Save livemehere/2cb7127ea35fcab8422de696509eec51 to your computer and use it in GitHub Desktop.
Save livemehere/2cb7127ea35fcab8422de696509eec51 to your computer and use it in GitHub Desktop.
Get Browser scrollbar width
  const getScrollbarWidth = () => {
    // Creating invisible container
    const outer = document.createElement("div");
    outer.style.visibility = "hidden";
    outer.style.overflow = "scroll"; // forcing scrollbar to appear
    document.body.appendChild(outer);

    // Creating inner element and placing it in the container
    const inner = document.createElement("div");
    outer.appendChild(inner);

    // Calculating difference between container's full width and the child width
    const scrollbarWidth = outer.offsetWidth - inner.offsetWidth;

    // Removing temporary elements from the DOM
    outer.remove();

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