Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since the previous solution does not work anymore (see original answer below), I've come across another solution which works for me and, according to <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth" rel="nofollow">MDN</a>, it should work in all browser, with IE starting from version 6. This solution to get the scrollbar width is even a bit simplified:</p> <blockquote> <ol> <li>Append a div without a scrollbar to the body and position it off screen</li> <li>Measure the client width of the div</li> <li>Set the div to have a scrollbar (using css overflow style)</li> <li>Measure the clientWidth of the div again</li> <li>Remove the div</li> <li>Return the difference of the two widths</li> </ol> </blockquote> <p>And the code would look like this:</p> <pre><code>function scrollbarWidth() { var div = $('&lt;div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"&gt;&lt;/div&gt;'); // Append our div, do our calculation and then remove it $('body').append(div); var w1 = div.prop('clientWidth'); div.css('overflow-y', 'scroll'); var w2 = div.prop('clientWidth'); $(div).remove(); return (w1 - w2); } </code></pre> <p>And <a href="https://jsfiddle.net/nv1cp1bs/2/" rel="nofollow">here</a> is a working jsFiddle.</p> <hr /> <h3>Original answer (for completeness sake)</h3> <p><a href="http://jdsharp.us/jQuery/minute/calculate-scrollbar-width.php" rel="nofollow">Here</a> is a solution to calculate the width of a scrollbar, which you can use in conjuction with some of the other answers here (and your own knowledge as far as I can tell).</p> <p>The idea is to do the following steps:</p> <blockquote> <ol> <li>Append two divs to the body and position them off screen</li> <li>Measure the width of the inner div</li> <li>Set the outer div to overflow</li> <li>Measure the width of the inner div (again)</li> <li>Remove the divs</li> <li>Return the difference of the two widths</li> </ol> </blockquote> <p>And here is the code, copied from the referenced page:</p> <pre><code>function scrollbarWidth() { var div = $('&lt;div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"&gt;&lt;div style="height:100px;"&gt;&lt;/div&gt;'); // Append our div, do our calculation and then remove it $('body').append(div); var w1 = $('div', div).innerWidth(); div.css('overflow-y', 'scroll'); var w2 = $('div', div).innerWidth(); $(div).remove(); return (w1 - w2); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload