问题描述
这是我拥有的 CSS:
.tab {
border: 0;
flex: 1 1 0;
min-height: 48px;
opacity: 1;
text-align: center;
z-index: 0;
}
.tab:not([data-selected]) {
border-radius: 0;
}
.tab[data-selected] {
background-color: $white;
border: 1px solid #eee;
z-index: 2;
}
.tab[data-selected]:first-of-type {
margin-right: -8px;
}
.tab[data-selected]:last-of-type {
margin-left: -8px;
}
.tab[data-selected]:not(:first-of-type):not(:last-of-type) {
margin-left: -8px;
margin-right: -8px;
}
.tab:first-of-type {
border-bottom-left-radius: 12px;
border-top-left-radius: 12px;
}
.tab:last-of-type {
border-bottom-right-radius: 12px;
border-top-right-radius: 12px;
}
这里有点问题:
.tab[data-selected]:not(:first-of-type):not(:last-of-type) {
margin-left: -8px;
margin-right: -8px;
}
我正在尝试选择中间孩子。我的 stylelint 是这样抱怨的:
Expected "`.tab[data-selected]:not(:first-of-type):not(:last-of-type)`" to have a specificity no more than "0,3,2"
我该如何更好地解决这个问题?
解决方法
选择器的总体特异性
.tab[data-selected]:not(:first-of-type):not(:last-of-type)
是 (0,4,0),即超过 (0,3,2) 的 1。
您可以增加 selector-max-specificity
以适应此选择器,因为差异很小。
或者,如果您不想这样做,您可以像这样重构您的 &[data-selected]
CSS 规则。默认情况下应用两个负边距,然后有选择地从 &:first-of-type
和 &:last-of-type
中删除负边距,从而消除双重否定的需要:
&[data-selected] {
background-color: $white;
margin-left: -8px;
margin-right: -8px;
border: 1px solid #eee;
z-index: 2;
&:first-of-type {
margin-left: 0; /* Preserve negative margin-right */
}
&:last-of-type {
margin-right: 0; /* Preserve negative margin-left */
}
}
请注意,两个嵌套规则中的边距方向交换了,因为我们试图保留现在存在的负边距,而不是将它们添加到以前不存在的位置。