Measure the width and height of an Html element in a Dart

I would like to know the exact size of an element without a border, border and padding, only the width and height of the innermost field (see image below).

I currently know about the function "getBoundingClientRect", which gives the size, including the border and padding. There is also a "client" property that returns Rect, including the complement.

So the question is how to get width and height without filling?

CSS box model

+7
source share
3 answers

Unfortunately, the DOM does not provide such functionality. This is why most libraries, such as jQuery, ExtJS, etc., provide helper methods. They essentially analyze the style and define it.

Here is an example:

<div style="width: 100px; height: 100px; padding: 5px; border: 1px solid #000"></div> 
 int getWidth(Element element) { var paddingLeft = element.style.paddingLeft.replaceAll('px', ''); // You may want to deal with different units. var paddingRight = element.style.paddingLeft.replaceAll('px', ''); return element.clientWidth - int.parse(paddingLeft) - int.parse(paddingRight); } 

And use:

 print(getWidth(query('#test'))); 

Result:

 100 

Notes:

  • You can deal with different types of units (px, pt, em, ...).
  • The box-sizing property also has an effect that you might want to test.

If I or you happen to find the time, maybe release the Pub package or something else. :)

+8
source

This pub package can predict the size of text (without margins, borders, and padding) that does not yet exist in the DOM: https://pub.dartlang.org/packages/textent

+1
source

Try the relatively recently introduced Element.contentEdge , which seems to be exactly what you want.

This Google employee comment lists a few more related methods that have also been added. Please note that at least some of them are still marked as experimental in the API docs, but they can be useful nonetheless.

0
source

All Articles