getBoundingClientRect() for element overflowing the container

1.4k views Asked by At

Suppose we have a text overflowing its container div:

console.log(document.querySelector("p").getBoundingClientRect().width)
#myDiv {
  width: 20px;
  background-color: wheat;
  border: 1px solid #ddd;
}
<div id="myDiv">
  <p>foobarfoobarfoobarfoobarfoobar</p>
</div>

As you can see the container div has a fixed width (20px) but even if the text is obviously bigger than that getBoundingClientRect() doesn't go over that container value.

Is there any alternative for getting the bounding rectangle of the text element in this situation?

1

There are 1 answers

0
sbgib On BEST ANSWER

Try setting display: inline-block; on the p element so that it has a specific width:

console.log(document.querySelector("p").getBoundingClientRect().width)
#myDiv {
  width: 20px;
  background-color: wheat;
  border: 1px solid #ddd;
}

p {
   display: inline-block;
}
<div id="myDiv">
 <p>foobarfoobarfoobarfoobarfoobar</p>
</div>