0

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.

http://jsfiddle.net/MjrMq/

Thank you!

Layne
  • 642
  • 1
  • 13
  • 32

1 Answers1

3

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.)

Cat
  • 66,919
  • 24
  • 133
  • 141
  • If I can say one thing careful with outerWidth the returned value are different with the browser. I tested this afternoon. http://stackoverflow.com/questions/12362376/convert-width-in-px-to-in-jquery-for-bootstraps-appended-labels-while-flui/12373979 – Charles Jourdan Sep 12 '12 at 20:08
  • @CharlesJourdan I don't have other browsers handy to check, but this is always something to worry about with dimensions. Good catch. – Cat Sep 12 '12 at 20:11