我正在尝试制作一个不依赖于预设列数的网格。我创建了一个小样本来展示这种情况:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Grid in HTML5 and CSS3</title>
<style>
* {margin:0;padding:0;}
.row {display:block;position:relative;clear:both;}
.row>* {display:block;position:relative;clear:both;float:left;clear:none;width:100%;}
.row>*:empty {width:0px;}
/* one column in the row */
.row>:nth-last-child(1):nth-child(1) {width:100%;}
/* two columns in the row */
.row>:nth-last-child(2):nth-child(1) {width:50%;}
.row>:nth-last-child(1):nth-child(2) {width:50%;}
/* three columns in the row */
.row>:nth-last-child(3):nth-child(1) {width:33.33%;}
.row>:nth-last-child(2):nth-child(2) {width:33.33%;}
.row>:nth-last-child(1):nth-child(3) {width:33.34%;}
.row>:empty:nth-last-child(3):nth-child(1)+:not(:empty) {width:66.66%;}
.row>:empty:nth-last-child(2):nth-child(2)+:not(:empty) {width:66.67%;}
article {margin:.5em;border:1px solid green;border-radius:.3em;padding:.5em; }
</style>
</head>
<body>
<section class="row">
<div>
<article>
<p>This row has only one child.</p>
</article>
</div>
</section>
<section class="row">
<div>
<article>
<p>This row has two children</p>
</article>
</div>
<div>
<article>
<p>This is the second child</p>
</article>
</div>
</section>
<section class="row">
<div>
<article>
<p>
This row has three children
</p>
</article>
</div>
<div>
<article>
<p>So this is col 2 of 3</p>
</article>
</div>
<div>
<article>
<p>And this is col 3 of 3.</p>
</article>
</div>
</section>
<section class="row">
<div></div>
<div>
<article>
<p>The first child of this row is empty so spanned with the second</p>
</article>
</div>
<div>
<article>
<p>This is the second column</p>
</article>
</div>
</section>
<section class="row">
<div>
<article>
<p>This is the first column</p>
</article>
</div>
<div></div>
<div>
<article>
<p>The second and third column are spanned</p>
</article>
</div>
</section>
</body>
</html>
我在 jsfiddle 上放了一个更大的样本 - 更详细地描述了这些问题
http://jsfiddle.net/jordenvanforeest/MDv32/
我现在的问题是,如果您希望此网格容纳 3 列以上,CSS 大小会呈指数级增长。所以我正在寻找其他解决方案。我试图做类似的事情
.row>:nth-last-child(an+b):nth-child(cn+d) {}
但是我的微积分技能有点生疏,我无法让它正常工作。帮助将不胜感激。
更新
三十点提供了一个使 CSS 变得更小的答案。这个小提琴是他建议的改进版本。
仍然欢迎任何其他建议。我的 12 列网格仍然需要 30K 来进行跨越。