6

I'm currently working on eliminating jQuery from some code that I've written, and I've got a portion of code in which I was computing both the inner and outer widths of some span elements. It seems like .getBoundingClientRect() works fine for getting the outer width of an element, but I'm a bit stuck on getting the inner width. (i.e. the width of the element sans padding and borders.)

I'm using d3 to create my spans, and I need to compute their inner widths so that I can effectively set the widths of some other elements in order to get them to line up. Is there a good way of getting inner width for a div without manually checking and subtracting the various .css properties that could affect it?

ckersch
  • 7,507
  • 2
  • 37
  • 44

4 Answers4

6

Not sure how stable this is, but the method that seems to be working is using window.getComputedStyle(element).width.

This gives the computed style as "95px", where 95 is the inner width (in pixels). I'm using parseInt(window.getComputedStyle(element).width) to get the inner width of the element as a number.

ckersch
  • 7,507
  • 2
  • 37
  • 44
  • 3
    Please note that the value returned by this also depends on the box-sizing css property. – neo Dec 18 '18 at 22:41
  • 1
    Specifically, this solution does not work if the web page sets `box-sizing: border-box` on all elements, which is probably common nowadays. – Šime Vidas Jul 03 '21 at 07:55
2

Taken from jQuery:

Math.max(element.scrollWidth, element.offsetWidth, element.clientWidth)
Inc33
  • 1,747
  • 1
  • 20
  • 26
1

You could try .offsetWidth. Here's a fiddle.

Justin Chmura
  • 1,939
  • 1
  • 15
  • 17
  • 1
    This seems to give the same result as `.getBoundingClientWidth()` (i.e. includes padding and borders). – ckersch Dec 23 '13 at 17:38
0
function innerWidth(elem) {
    if (elem != null && elem === elem.window) { // window
        return elem.document.documentElement.clientWidth;
    } else if (elem.nodeType === 9) { // document
        const doc = elem.documentElement;

        return Math.max(
            elem.body[ "scrollWidth" ], doc[ "scrollWidth" ],
            elem.body[ "offsetWidth" ], doc[ "offsetWidth" ],
            doc[ "clientWidth" ]
        );
    }
    return window.getComputedStyle(elem).width;
}
LeeChan
  • 1
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 09 '23 at 18:25