Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measure width and height of Html element in Dart

Tags:

dart

I would like to know the exact size of an element without margin, border and padding, just the width and height of the most inner box (see image below).

Currently i'm aware of the function "getBoundingClientRect" which gives the size including border and padding. There is also the "client" property which returns a Rect including the padding.

So the question is, how do i get the width and height without padding?

CSS box model

like image 954
bp74 Avatar asked Mar 26 '13 10:03

bp74


2 Answers

Unfortunately the DOM does not provide such functionality. That's why most libraries like jQuery, ExtJS, etc. provide helper methods. They essentially parse the style and figure it out.

Here's 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 the usage:

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

Result:

100

Notes:

  • You might consider dealing with different types of units (px, pt, em, ...).
  • The box-sizing property also has an effect you might want to check for.

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

like image 159
Kai Sellgren Avatar answered Nov 01 '22 15:11

Kai Sellgren


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

like image 43
Cristian Almstrand Avatar answered Nov 01 '22 15:11

Cristian Almstrand