Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does getBoundingClientRect only work locally?

Consider the follow HTML (JSFiddle link):

<div id="a" class="box">cat</div>
<div id="b" class="box rotate">cat</div>
<div id="c" class="box"><div class="rotate">cat</div></div>

and CSS:

.box    { font-size:500%; }
.rotate { transform: rotate(-90deg); }

Measuring the width and height of element id=a using .getBoundingClientRect()

$(a)[0].getBoundingClientRect().width
$(a)[0].getBoundingClientRect().height

gives the dimensions of (320,91). Measuring the same thing on element id=b gives the transposed dimensions (91,320). Wonderful.

However, when I try to measure element id=c which simply nests the rotation inside an inner div, I get the originally dimensions (320,91)! Shouldn't the bounding boxes for b and c be the same?

If not, how can I get the bounding box of c to report correctly?


If relevant, I'm using Chromium, Version 37.0.2062.120 Ubuntu 12.04 (281580) (64-bit).

like image 256
Hooked Avatar asked Sep 30 '22 04:09

Hooked


1 Answers

No, the rotated bit within c extends out of c, without changing its size. This should make it a bit clearer:

var bbox_a = document.getElementById("a").getBoundingClientRect();
snippet.log("a: " + bbox_a.width + "x" + bbox_a.height);

var bbox_b = document.getElementById("b").getBoundingClientRect();
snippet.log("b: " + bbox_b.width + "x" + bbox_b.height);

var bbox_c = document.getElementById("c").getBoundingClientRect();
snippet.log("c: " + bbox_c.width + "x" + bbox_c.height);
.box {
    font-size:500%;
}
.rotate {
    transform: rotate(-90deg);
}
#a {
    border: 1px solid black;
}
#b {
    border: 1px solid red;
}
#c {
    border: 1px solid green;
}
#c .rotate {
    border: 2px solid yellow;
}
<div id="a" class="box">cat</div>
<div id="b" class="box rotate">cat</div>
<div id="c" class="box">
    <div class="rotate">cat</div>
</div>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

(I removed the reliance on automatic globals a, b, and c above. It just makes me jittery to rely on automatic globals, they're so easily shadowed.)

BTW, you can visualize things like this using Chromium's dev tools: Right-click the element and choose "Inspect element", and it'll open the Elements panel in the dev tools. At that point, when your cursor is over the markup for the element in the Element's panel, dev tools will highlight that element (including its bounding box) on the page.

like image 138
T.J. Crowder Avatar answered Oct 01 '22 20:10

T.J. Crowder