【问题标题】:LESS add a whitespace on nth-child selectorLESS 在第 n 个子选择器上添加空格
【发布时间】:2022-01-09 02:44:54
【问题描述】:

我目前有这个酒糟代码:

.myclass{
    display:inline-block;
    overflow: auto;
    & li{
        display: none;
        &:nth-child(1),:nth-child(2),:nth-child(3){
            display:inline-block;
        }
    }
}

如您所见,我想要的是只显示前三个 li 元素,其余的将显示为 none。但是编译使这个输出:

.myclass{
    display:inline-block;
    overflow: auto;
}
.myclass li{
    display: none;
}
.myclass li:nth-child(1),
.myclass li :nth-child(2),
.myclass li :nth-child(3) {
    display: inline-block;
}

如您所见,:nth-child(2):nth-child(3) 中有一个空格,所以只有第一个孩子工作正常。

如何删除这个空格?

【问题讨论】:

  • 您应该将& 放在列表中的每个选择器之前(因为& 仅适用于它出现的选择器,而不适用于“所有后续”选择器)。简单来说,应该是:&:nth-child(1), &:nth-child(2), &:nth-child(3)(这是三个不同的选择器)。
  • 随意添加答案,选择它作为最佳答案

标签: css css-selectors less whitespace


【解决方案1】:

您的问题是您仅在第一个 :nth-child 声明中使用 LESS's immediate parent selector (&) 而不是在其他两个声明中。很明显,如果我们在每个声明之间放置一个换行符:

&:nth-child(1),
:nth-child(2),
:nth-child(3){
    display:inline-block;
}

要解决此问题,您只需将 & 放在其他两个 :nth-child 声明之前:

&:nth-child(1),
&:nth-child(2),
&:nth-child(3){
    display:inline-block;
}

此外,您不需要在li 选择器之前使用&

.myclass {
    li {
        ...
    }
}

【讨论】:

    【解决方案2】:

    为了能够做到这一点,你可以制作一个重复的结构

    .myclass{
      display:inline-block;
      overflow: auto;
      & li{
          display: none;
          /* In range() pass as an argument the number of iterations you need to perform */
          each(range(3), {
            /* And to the argument of nth-child() you pass the value (the current iteration number) */
            &:nth-child(@{value}) {
              display:inline-block;
            } 
          }) 
      }
    }
    

    输出:

    .myclass {
      display: inline-block;
      overflow: auto;
    }
    .myclass li {
      display: none;
    }
    .myclass li:nth-child(1) {
      display: inline-block;
    }
    .myclass li:nth-child(2) {
      display: inline-block;
    }
    .myclass li:nth-child(3) {
      display: inline-block;
    }
    

    有关更多信息,我推荐文档:https://lesscss.org/functions/#list-functions-each

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多