Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

methods for element width/height

Tags:

javascript

css

Question: Is there a scenario where getBoundingClientRect and window.getComputedStyle would differ in width or height?

I just found a inconsistent width (see under) in IE when a element has box-sizing where window.getComputedStyle returns the wrong value.

So I thought about overriding just width and height with values from getBoundingClientRect but not sure if there are cases where that would fail.

Example of the problem (broken in IE): http://jsfiddle.net/bwPM8/

var box = document.querySelector('.box');
var gBCR_width = box.getBoundingClientRect().width; // always 200
var wGCS = window.getComputedStyle(box).width; // 200 some browsers, 160 in IE
like image 308
Rikard Avatar asked Jul 10 '14 08:07

Rikard


Video Answer


1 Answers

Yes, there are several differences between these two functions.

getBoundingClientRect() will return a text rectangle object that encloses a group of text rectangles (the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element). The latter, getComputedStyle(), will return the computed CSS style of that element, after applying all CSS.

Therefore the resulting width and height can be drastically different.

For instance, by simply applying a transform to that element you already change the width that is returned by getBoundingClientRect():

http://jsfiddle.net/epW3c/

Moreover, even if you add a border or padding to your element, the width and height will be different in both cases.

Depending on the version of IE you're testing this on, you might be experiencing the infamous Internet Explorer box model bug which causes the interpretation of the dimensions of the element to be wrong. Make sure you're not running your page in quirks mode by adding the doctype properly.

like image 89
MMM Avatar answered Sep 22 '22 01:09

MMM