我正在构建砌体网格,但在计算出选择适当元素的代数时遇到了困难。
- 2x 宽样式的元素:1, 7, 11, 17, 21, 27, ...
- 2 倍高样式的元素:2、6、12、16、22、26、...
所有其他元素将由默认样式处理。
标记是:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
...
</ul>
我无法完全找到用于我的 :first-child
伪类的模式。我附上了我要实现的目标的图片。
有没有数学天才准备好迎接[可能非常简单]的挑战?
最佳答案
你可以这样对序列进行分类:
1, 7, 11, 17, 21, 27, ... 包含 2 个子序列:
- 1, 11, 21, ...
- 7, 17, 27, ...
所以我们可以使用 2 个选择器::nth-child(10n + 1)
和 :nth-child(10n + 7)
。
2, 6, 12, 16, 22, 26, ... 包含 2 个子序列:
- 2, 12, 22, ...
- 6, 16, 26, ...
所以我们可以使用 2 个选择器::nth-child(10n + 2)
和 :nth-child(10n + 6)
。
根据您的图像,我可以看到所有 1, 11, 21, ...
和 7, 17, 27, ...
都应该有宽度about 66.66%
(2/3) 和更大的 height
与其他单元格的默认高度相比。所有2, 12, 22, ...
和 6, 16, 26, ...
的高度应该与 1, 11, 21, ...
和 7, 17, 27, ...
并且它们与其他默认单元格具有相同的宽度(大约 33.33%
或 1/3
).
所以我们可以这样设置 ul
的样式:
ul {
width:500px;
list-style:none;
border:20px solid gray;
overflow:auto;
padding:0;
}
ul > li {
display:inline-block;
float:left;
width:33.33%;
height:50px;
border:2px solid lightgray;
box-sizing:border-box;
text-align:center;
}
/* this is just to center the text vertically */
ul > li:before {
content:'';
display:inline-block;
height:100%;
vertical-align:middle;
}
ul > li:nth-child(10n + 1), ul > li:nth-child(10n + 7) {
width:66.66%;
height:80px;
}
ul > li:nth-child(10n + 2), ul > li:nth-child(10n + 6){
height:80px;
}
Demo.
在上面的演示中,您可以看到所有内部元素周围都有一个 2px
的内边框,并且与 ul
的边框相邻,需要将其删除以适当的单元格为目标并删除适当的边框。这是 Updated Demo 哪个更复杂。
关于css - 使用 :nth-child pseudo class, 是否可以选择由 2 个元素组分隔的 3 个元素组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23814673/