除非您希望有嵌套表或实例,而您只想针对 colgroups 内(而不是外部)的 cols,否则您会有很多冗余。
table.test {
// must the col appear within a colgroup?
col {
$i: 1;
@each $w in (10em, 5em, 10em, 20em, 15em) {
&:nth-child(#{$i}) {
width: $w;
}
$i: $i + 1;
}
}
// a td can't appear outside of a tr
tbody td {
$i: 1;
@each $a in (left, left, center, right, left) {
// is the alignment only for direct descendants of the td necessary?
&:nth-child(#{$i}) {
text-align: $a;
}
$i: $i + 1;
}
}
}
生成:
table.test col:nth-child(1) {
width: 10em;
}
table.test col:nth-child(2) {
width: 5em;
}
table.test col:nth-child(3) {
width: 10em;
}
table.test col:nth-child(4) {
width: 20em;
}
table.test col:nth-child(5) {
width: 15em;
}
table.test tbody td:nth-child(1) {
text-align: left;
}
table.test tbody td:nth-child(2) {
text-align: left;
}
table.test tbody td:nth-child(3) {
text-align: center;
}
table.test tbody td:nth-child(4) {
text-align: right;
}
table.test tbody td:nth-child(5) {
text-align: left;
}
或者...
$list: 10em left, 5em left, 10em center, 20em right, 15em left;
table.test {
// must the col appear within a colgroup?
$i: 1;
@each $child in $list {
col {
&:nth-child(#{$i}) {
width: nth($child, 1);
}
}
// a td can't appear outside of a tr
tbody td {
// is the alignment only for direct descendants of the td necessary?
&:nth-child(#{$i}) {
text-align: nth($child, 2);
}
}
$i: $i + 1;
}
}
生成:
table.test col:nth-child(1) {
width: 10em;
}
table.test tbody td:nth-child(1) {
text-align: left;
}
table.test col:nth-child(2) {
width: 5em;
}
table.test tbody td:nth-child(2) {
text-align: left;
}
table.test col:nth-child(3) {
width: 10em;
}
table.test tbody td:nth-child(3) {
text-align: center;
}
table.test col:nth-child(4) {
width: 20em;
}
table.test tbody td:nth-child(4) {
text-align: right;
}
table.test col:nth-child(5) {
width: 15em;
}
table.test tbody td:nth-child(5) {
text-align: left;
}