2

How can I compute the exact width of a block element excluding padding, scroll bar, border, and margin? I know I can use $(element).width(), but jQuery does not compute the exact value because it silently rounds up the fractional part. (Please see my previous question here.)

The only way I can think of is to use .getBoundingClientRect().width and subtract what's not needed. There's got to be something better than this, but what is it?

Community
  • 1
  • 1
CookieEater
  • 2,237
  • 3
  • 29
  • 54
  • 1
    How is this actually different from your previous question? Except for it being width instead of height? Seems the answer is the same and there's no real need for two questions. – Matt Burland Mar 05 '14 at 19:19
  • possible duplicate of [Why does jQuery's height() automatically rounds up the value?](http://stackoverflow.com/questions/21777668/why-does-jquerys-height-automatically-rounds-up-the-value) – Matt Burland Mar 05 '14 at 19:19
  • Sorry, it is confusing, but this is NOT the same question. `getBoundingClientRect().width` includes padding, scroll bar and border. I want to calculate the width without them. – CookieEater Mar 05 '14 at 19:26

2 Answers2

3

With Javascript you can also use getComputedStyle(). Don't know about jquery alternative

var element = document.getElementById("a");
alert(window.getComputedStyle(element).width);
Ankur Aggarwal
  • 2,993
  • 5
  • 30
  • 56
-3

jQuery is not silently rounding the value. jQuery is returning the browser computed value. Since browsers can not display a fraction of a pixel the browser itself is computing a more appropriate value for the element. jQuery is actually returning the correct and most precise value.

take this code for example:

<div style="width:201px;">
  <div style="width:50%;"></div> <!-- this renders as 100px, not 100.5px -->
</div>

There is 1 div with a width of 50% inside an element that is 201px wide. based on your assumptions, each div should have a width of 100.5px. However, If you inspect the child element using any browsers development tools you will notice that it is actually being rendered as just 100px wide with no fractional value.

jkofron.e
  • 5,043
  • 1
  • 17
  • 16