I have a container div. Inside that container div are a number of smaller divs that I would like to space out the width of the parent div while adding a gap between each. The number of inner divs will change.
I’m using this formula (containerWidth-(numberOfBars*gap))/numberOfBars to figure out each bar’s space and then trying jquery to modify the css dynamically.
I can’t get the width to change or get them to space out.
A fiddle is attached.
Thank you!
You should familiarize yourself with
outerWidth(); I think it suits this situation quite well. Whentrueis passed, it will take the outer width of a container, including the margin. Therefore, when you have an item of width0, 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
barandcontainervariables, neither of which was defined. Nor had you used$(document).ready(...)or anything similar.First, I set your
widthto0(to get proper outer width). Then I calculated the width, as such: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 - 1or whatnot.)