You should familiarize yourself with outerWidth()
; I think it suits this situation quite well. When true
is passed, it will take the outer width of a container, including the margin. Therefore, when you have an item of width 0
, and take the outer width, it will be only the padding/margin/border you don't want included in the width.
Next, I played with your logic a bit. I took the total width of each bar instead of the inner width, then used the outer width to get the inner width from it. (That is, Container width / n -> Outer Width; Subtract padding -> Inner Width
.)
Last thing I want to note before sharing the updated fiddle is: Please, please, please, in the future, test your fiddle first. You had created bar
and container
variables, neither of which was defined. Nor had you used $(document).ready(...)
or anything similar.
First, I set your width
to 0
(to get proper outer width). Then I calculated the width, as such:
var barOuterWidth = Math.floor(containerWidth / n);
var barInnerWidth = barOuterWidth - $(".bar").outerWidth(true);
Lastly, I used 'width': barInnerWidth,
to set the width.
The result is in this jsFiddle. Notice there is a margin gap on the right; I'm sure you can find a way to alleviate this. (i == n - 1
or whatnot.)