I've given 3 div
s a class of col-xs-4
to make them spread out evenly. But this only works if there are 3 div
s. What if the number changes? How can I dynamically change the col-xs-#
to adjust correctly so they are still spread out evenly? I can't pass any number or marker from my JS file to the css, so not sure how I would do this.
Asked
Active
Viewed 2,591 times
1

stackjlei
- 9,485
- 18
- 65
- 113
1 Answers
3
var childCount = document.getElementById("myDIV").childElementCount;
for(i = 0; i < childCount; i++) {
document.getElementById("myDIV").children[i].className = "";
document.getElementById("myDIV").children[i].className = "col-xs-" + (12/childCount);
}
This javascript first gets the number of children in your bootstrap row (in this case it has id myDIV), then it loops over these children while clearing the classes and setting a new col-xs-* class, based on childcount.
See following jsfiddle for the code in action: https://jsfiddle.net/vf65vooL/3/

Ruben Pirotte
- 386
- 2
- 11
-
fair point, let me find a workaround. First idea is drop the decimals but then the entire width wont be used. @stackjlei how do you want this issue to be solved? – Ruben Pirotte Sep 01 '16 at 09:35
-
Using the bootstrap grid system the only equal columns we can make (without workarounds) are for 1, 2, 3, 4, 6 and 12 columns on a row. How to make equal rows for another amount of columns is another question, and requires a lot of tweaking. This is a good start to figure it out: [http://stackoverflow.com/questions/10387740/five-equal-columns-in-twitter-bootstrap](http://stackoverflow.com/questions/10387740/five-equal-columns-in-twitter-bootstrap) – Ruben Pirotte Sep 01 '16 at 09:48
-
mine would only have 3 or 2 or 1 divs, so your answer works for me! – stackjlei Sep 01 '16 at 10:11