I've been searching everywhere for a method to accurately determine the width of an element without rounding. The reason behind this is that I have multiple elements floated to the left with display inline-block and I am attempting to automatically adjust the text within them so they fill up the entire width of the container div. Here's my approach:
- Start with a small font size, like 1
- Apply that font size to all text elements
- Calculate the combined width of all floated elements
- If it's smaller than the container width, increment the font size by a small amount
- Repeat steps 2-4 until you reach the maximum font size
The issue arises when there is leftover space not being used effectively. This is likely due to the fact that when I increase the font size in small increments (e.g. 0.01), the element widths don't change precisely because of rounding down. I can keep increasing the font size without seeing any changes in width until it eventually rounds up, causing the total width to exceed the limit. You can see this behavior illustrated in this JSFiddle example here:
The javascript code may seem complex, but essentially it initially uses larger font size increments to save time, gradually reducing the increments as it approaches the target size for greater accuracy.
I've attempted utilizing methods such as:
$(this).width()
parseFloat($(this).css("width"))
window.getComputedStyle
However, none of them provided the desired solution.