【问题标题】:Selector is exceeding selector-max-specificity选择器超出选择器最大特异性
【发布时间】:2021-04-19 13:51:49
【问题描述】:

这是我拥有的 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"

我该如何以更好的方式解决这个问题?

【问题讨论】:

    标签: css css-selectors css-specificity stylelint


    【解决方案1】:

    选择器的总体特异性

    .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 */
            }
        }
    

    请注意,边距方向在两个嵌套规则中交换,因为我们试图保留现在存在的负边距,而不是在以前不存在的地方添加它们。

    【讨论】:

    • 一种假设的替代方案以 .tab[data-selected]:not(:first-of-type, :last-of-type) 的形式存在,具有特异性 (0,3,0),除了 Safari 和 Firefox 以外的任何地方都不支持它......后者才刚刚开始一个月前支持它,在前者之后五年多。呃。
    猜你喜欢
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 2010-12-28
    • 2012-05-25
    相关资源
    最近更新 更多