Search code examples
javascriptcsssizepercentagecomputed-style

Error with computed size of relative-size HTML elements in javascript


My window object has a width of 1361px.

A container div has its width set to 90%, that theorically makes 1224.9px.

However, the computed size of it ( $("#mycontainer").width() ) returns 1225px. FYI, the computed number seems to come from the browser itself, not jQuery.

Now, the problem is that if I put two floating divs in it, respectively 1000px and 225px, they will NOT fit on the same line, allegedly because 1225px > 1224.9px. At least in FF and Chrome, not tested elsewhere.

If I set the container a fixed size of 1225px, then the two divs will be back on the same line, which confirms in my mind that the browser does not use the superior-rounded computed size to know how much space is actually available for children to occupy.

I wanted to know if anybody knew how to solve this. I am not even sure how to get the percentage size of the container to do the maths myself like this :

var width = Math.floor($(window).width * $("#mycontainer").percentageWidth() / 100)

Solution

  • CSS display: flex; is a good way to fix these quirks nowadays.