Starting off, I found this question quite intriguing and initially thought that flexbox would be the perfect solution. Despite experimenting with various flexbox setups, I couldn't crack this particular problem. So, here's a unique approach using floating, clearing, and media queries.
In this scenario, I assumed each row contains a minimum of 3 and a maximum of 9 boxes. However, you can modify this solution to accommodate anywhere from 1 to over 9 boxes.
Below is the HTML code:
<div class="grid">
<div></div>
<div></div>
...
</div>
Here's the CSS code which includes a small reset to remove any default browser padding or margins that might interfere with sizing, as well as styling for the grid and its child div elements:
* {
margin: 0;
padding: 0;
}
.grid {
display: table;
outline: 1px solid blue;
min-width: 330px;
margin: 0 auto;
}
.grid > div {
width: 100px;
height: 61px;
margin: 5px;
background-color: teal;
float: left;
}
The use of the container block was unnecessary due to displaying .grid as a table. By setting it up this way, .grid acts as a block wrapping around its children, while 'margin: 0 auto' centers it on the page. The min-width property ensures at least three blocks per line. Since floats don't collapse when used in a table element, there's no need for explicit float clearing (e.g., clearfix).
Each .grid div child occupies 110px horizontally (100px width + 10px margin on both sides), a crucial value for the upcoming media queries:
@media screen and (min-width: 330px) and (max-width: 439px) {
.grid > div:nth-of-type(3n + 1) {
clear: left;
}
}
...
The media queries adjust the layout based on screen width to manage the number of blocks per line efficiently.
For more insight into the implementation and visuals, refer to this fiddle link: http://jsfiddle.net/5hWXw/. Make sure to resize the preview window to observe the changes.