I have multiple divs with a fixed width and height (think about some sort of catalog view with article pictures). Now I want to show them similar to the behavior of float:left. This ensures that the larger your browser window is, the more divs are shown in one row.
The downside of the float:left solution is, that there is a big white gap on the right side, until another div will fit. Now I have the job to distribute the divs evenly one the page, and instead of a big white gap on the right side, there should be evenly distributed gaps between the single divs.
A solution in JavaScript is easy: http://dl.dropbox.com/u/2719942/css/columns.html
You can see, if you resize the browser window, it behaves similar to float:left, but the space is evenly distributed between the boxes. The column and row count is dynamically calculated with JavaScript:
function updateLayout() {
var boxes = document.getElementsByClassName('box');
var boxWidth = boxes[0].clientWidth;
var boxHeight = boxes[0].clientHeight;
var parentWidth = boxes[0].parentElement.clientWidth;
// Calculate how many boxes can fit into one row
var columns = Math.floor(parentWidth / boxWidth);
// Calculate the space to distribute the boxes evenly
var space = (parentWidth - (boxWidth * columns)) / columns;
// Now let's reorder the boxes to their new positions
var col = 0;
var row = 0;
for (var i = 0; i < boxes.length; i++) {
boxes[i].style.left = (col * (boxWidth + space)) + "px";
boxes[i].style.top = (row * boxHeight) + "px";
if (++col >= columns) {
col = 0;
row++;
}
}
}
Now I wonder if there is a solution without JavaScript? I would prefer a CSS-only solution, because I will have possibly up to hundreds of divs on one page.
I looked into CSS3 Flexible Box Layout, but this seems to be only useful for fixed column layouts. In my example, the column count gets calculated dynamically. Then I tried CSS3 Multi-column Layout, which I could get something similar working, but the divs are aligned vertically, cut off in the inside, and the browser support isn't there yet. This seems more useful for text, but in my case I have fixed divs with pictures, that shouldn't get cut off.
So my question is: can I realize something like this without JavaScript?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…