As I mentioned in my comment that I wasn't sure if it could be done with CSS alone, I created a quick JS/jQuery solution to calculate the width based on the first row of contents.
function resizeGrid() {
var rowPos = 0;
var col = 0;
$('.b').removeAttr('style');
$('.c').each(function() {
var thisRowPos = $(this).offset().top;
if (thisRowPos != rowPos) {
if (rowPos != 0) {
/* Break out of the $.each() loop */
return false;
} else {
col++;
}
rowPos = thisRowPos;
} else {
col++;
}
});
$('.b').css('width', $('.c').outerWidth(true) * col + 'px');
console.log('Number of columns: ' + col);
}
$(window).on('resize', resizeGrid);
resizeGrid();
* {
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.a {
border: 1px solid red;
}
.b {
margin: 0 auto;
background: lightgreen;
}
.b:after {
content: '';
display: block;
width: 100%;
height: 0;
clear: both;
}
.c {
padding: 5px;
height: 100px;
display: inline-block;
float: left;
}
.c table {
background-color: blue;
height: 100%;
width: 100%;
float: left;
}
.c table td {
vertical-align: top;
}
body {
padding: 50px;
}
<div class="a">
<div class="b">
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
<div class="c">
<table>
<tbody>
<tr>
<td>x x x x x</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…