I am dealing with a situation where I have a container that holds multiple child elements such as boxes or sections.
<section>
<div>Box 1</div>
<div>Box 2</div>
<div>Box 3</div>
<div>Box 4</div>
<div>Box 5</div>
<div>Box 6</div>
<div>Box 7</div>
<div>Box 8</div>
<div>Box 9</div>
<div>Box 10</div>
</section>
These child elements each have a minimum width and are floated left. Depending on the parent container's width, a specific number of children should be displayed in a row.
section {
min-width: 150px;
font-family: 'Segoe UI', Ubuntu, sans-serif;
}
div {
min-width: 150px;
height: 150px;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
float: left;
margin: 0 3px 3px 0;
padding: 3px;
background-color: lightblue;
border: 1px solid #000;
}
To achieve this layout, I would like the children to fill the entire width of the parent container if it is between multiples of the child element's width. For example, if the parent container's width is 660px, each child should be 165px wide. Additionally, any changes in the parent container's width should automatically adjust the children's widths.
I have explored using media queries for my specific case, but I am seeking a more general solution that can handle variable parent container widths. While I am open to utilizing JavaScript/jQuery, the solution should gracefully degrade in older browsers and be compatible with modern browsers like IE 10+, Firefox, Chrome, and Safari.
Initially, I attempted to use flexbox, but encountered issues in Firefox due to its limited support for single-line flexbox. As a result, I turned to JavaScript based on Siddhartha Gupta's suggestion. However, there seems to be a bug where sometimes the rows do not completely fill the available space.
$(window).resize(function () {
var sectionWidth = $('section').width(),
childWidth = (sectionWidth / Math.floor(sectionWidth/150)) - 3;
$('section').children().css({
'width': childWidth + 'px'
});
});