Alternately, you can do this with no JS code with flex-box CSS, if you don't need to accommodate ancient browsers.
Unfortunately, flex-box is a changing standard, so you would need to provide both browser-prefixed and new-standard CSS.
But it is really ideal for this use case.
For simplicity, showing only "old" webkit CSS (supported by all current Webkit browsers):
- <div class='container'>
- <div>Content</div>
- <div>Content</div> <!- add as many as you want here -->
- </div>
(You need to have a container.)
- .container {
- width: 100%;
- display: -webkit-box;
- -webkit-box-orient: horizontal;
- }
- .container > div {
- display: block;
- -webkit-box-flex: 1;
- }
As you add or remove <divs>, the boxes will adjust so that each one takes equal space. No Javascript needed.
The "1" is the width ratio to be applied to the element. All of the children have the value 1, so they all will be equal width.
(If you wanted, for example, one of the boxes to be twice as wide as all of the others, you would give it a -webkit-box-flex of 2.)
This is all you need if you are, saying, making a PhoneGap app for iOS or Android.
You would need additional alternative-prefixed CSS, plus the new standard CSS if you're doing this for the web. If you're using Sass, Sass libraries like Bourbon can help with this.
box-flex is our way out of "float hell". A big plus is that it avoids layout complications with borders/margin which are evident in Jay's solution.
Here's a fiddle (only for WebKit)