I need to organize a varying number of items into columns. The sizes of both the items and container are unknown, as well as how many columns will fit or what width they should be. I want the browser to arrange the items in as many columns as possible without exceeding the container's width, while minimizing its height.
This approach works, but is there a more efficient method? Can this be achieved without relying on jQuery? Is there a way to gracefully degrade for older browsers that lack certain features (perhaps organizing items in rows instead of columns)?
<style>
#wrapper {
column-width: 100px; /* the jQuery will change this */
padding: 20px;
border: 2px solid blue;
}
.item {
padding: 50px;
border: 2px solid green;
}
</style>
<div id="wrapper">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Find the maximum width among the children elements.
var maxWidth = 0;
jQuery('#wrapper .item').each(function() {
var width = jQuery(this).outerWidth(true);
if (width > maxWidth) {
maxWidth = width;
}
});
// Set the column-width of the wrapper to match the maximum width.
jQuery('#wrapper').css('column-width', maxWidth + 'px');
</script>