我的网格数学辅助:n-child(an + b)

Jor*_*est 12 css css-selectors css3

我正在尝试制作一个不依赖于预设列数的网格.我创建了一个小样本来显示情况:

<!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>
Run Code Online (Sandbox Code Playgroud)

我在jsfiddle上放了一个更大的样本 - 更详细地描述了问题

http://jsfiddle.net/jordenvanforeest/MDv32/

我现在的问题是,如果你想让这个网格容纳超过3列,CSS大小会成倍增长.所以我正在寻找其他解决方案.我试着做点什么

.row>:nth-last-child(an+b):nth-child(cn+d) {} 
Run Code Online (Sandbox Code Playgroud)

但我的微积分技术有点生疏,我无法让它正常工作.非常感谢帮助.

更新

thirtydot提供了一个使CSS更小的答案.这个小提琴是他提出的改进版本.

任何其他建议仍然欢迎.我的12列网格仍需要30K的跨度.

thi*_*dot 5

你可以display: table结合使用table-layout: fixed类似的东西.

浏览器支持:http://caniuse.com/css-table(但这里的限制因素是:not():empty)

请参阅: http ://jsfiddle.net/thirtydot/MDv32/3/

如您所见,它看起来几乎相同.凭借一些独创性,您应该能够使用我使用的技术复制演示中的大部分功能.我在我停止的演示中注释掉了HTML.

CSS:

.row {
    display: table;
    table-layout: fixed;
    width: 100%;
}
.row > * {
    display: table-cell;
}
.row > :empty {
    display: none;
}
/* for example: */
.row > :empty + :not(:empty) + :last-child:not(:empty) {
    width: 33.33%;
}
Run Code Online (Sandbox Code Playgroud)