问题描述
我将这些CSS选择器重构为Sass:
I'm refactoring these CSS selectors over to Sass:
#romtest .detailed th:nth-child(2),
#romtest .detailed th:nth-child(4),
#romtest .detailed th:nth-child(6),
#romtest .detailed td:nth-child(2),
#romtest .detailed td:nth-child(3),
#romtest .detailed td:nth-child(6),
#romtest .detailed td:nth-child(7),
#romtest .detailed td.last:nth-child(2),
#romtest .detailed td.last:nth-child(4) {
background:#e5e5e5;
}
...然后想到了:
#romtest .detailed {
th:nth-child {
&(2), &(4), &(6) {
background:#e5e5e5;
}
}
td:nth-child {
&(2), &(3), &(6), &(7) {
background:#e5e5e5;
}
}
td.last:nth-child {
&(2), &(4) {
background:#e5e5e5;
}
}
}
不幸的是,这引发了错误:
Unfortunately this is throwing an error:
我也知道这样做会更好,因为我是:
I also know this could be better because I'm:
- 重复背景颜色
- 重复数字-即(2)和(6)
我应该如何重构这些选择器?
How should I refactor these selectors?
推荐答案
我会谨慎尝试在这里变得太聪明了。我认为这确实令人困惑,使用更高级的 nth-child
参数只会使其变得更加复杂。至于背景色,我只是将其设置为变量。
I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child
parameters will only make it more complicated. As for the background color I'd just set that to a variable.
在我想出自己太聪明可能是一件坏事之前,我想出了这里的内容。
Here goes what I came up with before I realized trying to be too clever might be a bad thing.
#romtest {
$bg: #e5e5e5;
.detailed {
th {
&:nth-child(-2n+6) {
background-color: $bg;
}
}
td {
&:nth-child(3n), &:nth-child(2), &:nth-child(7) {
background-color: $bg;
}
&.last {
&:nth-child(-2n+4){
background-color: $bg;
}
}
}
}
}
,这是一个快速演示:
and here is a quick demo: http://codepen.io/anon/pen/BEImD
----编辑----
避免重新键入背景色
的另一种方法:
Here's another approach to avoid retyping background-color
:
#romtest {
%highlight {
background-color: #e5e5e5;
}
.detailed {
th {
&:nth-child(-2n+6) {
@extend %highlight;
}
}
td {
&:nth-child(3n), &:nth-child(2), &:nth-child(7) {
@extend %highlight;
}
&.last {
&:nth-child(-2n+4){
@extend %highlight;
}
}
}
}
}
这篇关于Sass n子嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!