我想遍历我的表中匹配每个元素的所有<td>
元素到我在一个名为$ options-colors的sass地图中设置的颜色。目前我绊倒了,因为只有前3种颜色不断重复,因为每次都有新的<tr>
。我知道每次我的索引可被3整除时我需要递增<tr>
nth-of-type
或nth-child
,但我不确定如何将它们拼凑在一起,是否有人可以解释我如何才能做到这一点?
SCSS
table {
width: 100%;
tr {
@for $i from 1 through length($option-colours) {
/*
&:nth-child(#{$i}) {
if $i % 3 == 0 increment?
}
*/
td {
width: 33.3333%;
height: 100px;
&:nth-of-type(#{$i}) {
background: nth($option-colours, $i);
}
}
}
}
}
Codepen: http://codepen.io/styler/pen/oCKfJ?editors=110
HTML
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
答案 0 :(得分:0)
基本上,我创建了一些变量来跟踪我们应该设置哪一行以及哪个单元格。在循环的三次迭代之后,单元计数器被重置为1并且行计数器递增。我不确定这样组织大型SASS循环的最佳实践是什么,所以欢迎任何反馈。
http://codepen.io/sdsanders/pen/nchtb?editors=110
table {
width: 100%;
$row: 1;
$cell: 1;
tr {
@for $i from 1 through length($option-colours) {
&:nth-child(#{$row}) {
td {
&:nth-child(#{$cell}) {
background: nth($option-colours, $i);
}
$cell: $cell + 1;
@if $cell == 4 {
$cell: 1;
$row: $row +1;
}
}
}
}
td {
width: 33.3333%;
height: 100px;
}
}
}
相关的CSS输出如下所示:
table tr:nth-child(1) td:nth-child(1) {
background: #fcfcfc;
}
table tr:nth-child(1) td:nth-child(2) {
background: #ebebea;
}
table tr:nth-child(1) td:nth-child(3) {
background: #d7d7d6;
}
table tr:nth-child(2) td:nth-child(1) {
background: #c2c2c1;
}
...
答案 1 :(得分:0)
nth-child和nth-of-type选择器只计算兄弟元素。为了使您的CSS工作,您的标记需要将所有的td元素都作为兄弟姐妹(例如,在同一行中)。
要保留当前的标记,您必须告诉Sass您希望拥有多少列或行。此代码允许您指定每行的单元格数:
http://codepen.io/cimmanon/pen/vCLsm
$option-colours: (
hsla(60,1,99,1),
hsla(60,1,92,1),
hsla(60,1,84,1),
hsla(60,1,76,1),
hsla(60,1,68,1),
hsla(60,1,60,1),
hsla(60,1,52,1),
hsla(60,1,44,1),
hsla(60,1,36,1),
hsla(60,1,28,1),
hsla(60,1,20,1),
hsla(60,1,12,1)
);
$cells: 3;
table {
width: 100%;
td {
width: 33.3333%;
height: 100px;
}
@for $i from 1 through length($option-colours) {
$row: ceil($i / $cells);
tr:nth-child(#{$row}) {
$cell: $cells - ($row * $cells - $i);
td:nth-child(#{$row}n+#{$cell}) { // `#{$row}n+` is optional
background: nth($option-colours, $i);
}
}
}
}
输出:
table tr:nth-child(1) td:nth-child(1n+1) {
background: #fcfcfc;
}
table tr:nth-child(1) td:nth-child(1n+2) {
background: #ebebea;
}
table tr:nth-child(1) td:nth-child(1n+3) {
background: #d7d7d6;
}
table tr:nth-child(2) td:nth-child(2n+1) {
background: #c2c2c1;
}
table tr:nth-child(2) td:nth-child(2n+2) {
background: #aeaead;
}
table tr:nth-child(2) td:nth-child(2n+3) {
background: #9a9a98;
}
table tr:nth-child(3) td:nth-child(3n+1) {
background: #868683;
}
table tr:nth-child(3) td:nth-child(3n+2) {
background: #71716f;
}
table tr:nth-child(3) td:nth-child(3n+3) {
background: #5d5d5b;
}
table tr:nth-child(4) td:nth-child(4n+1) {
background: #484847;
}
table tr:nth-child(4) td:nth-child(4n+2) {
background: #343432;
}
table tr:nth-child(4) td:nth-child(4n+3) {
background: #1f1f1e;
}