lonewarrior556 lonewarrior556 - 6 months ago 25
Javascript Question

Can I measure partial-pixel-acurate width of elements

This has been bugging me for a long time. I am trying to do something simple, float li elements in a ul container, and give the li elements hover effect. Code looks like this:
All css has been rest, the elements are display block, and class clear add a " " clear both display block after element

<ul class="clear">
<li>one</li>
<li>two</li>
<li>three</li>
</ul>

ul > * { float: left; border: 1px solid black }
li{ padding: 10px;}
li:hover{ background-color: white; }


Now for some reason( maybe my font) the width of the ul changes in different browsers, So I cannot hard code the width of the ul to fit all the li's perfectly; Fine. so What I do is after everything loads, I measure every li's width and add it up and make that the width of the ul.

However this also fails since jquery.width()/offsetwidth/.outerWidth returns only whole numbers, and some of the elements have partial pixels like .34px and the width is either slightly too wide (results in gap) or to small and the the floated elements drop to the next line.

Is there a way to measure width with more accuracy?

Answer

This should do it for you, see fiddle for example https://jsfiddle.net/c259LrpL/28/

$(".clear")[0].getBoundingClientRect().width