【问题标题】:SCSS nth-child in for loop? [duplicate]SCSS nth-child 在 for 循环中? [复制]
【发布时间】:2015-04-21 00:45:31
【问题描述】:

我试图创建一个循环来创建许多具有匹配内容的 nth-child 选择器:

$show-numbers: true;

@if $show-numbers {
  @for $i from 1 through 5 {
    &:nth-child(1) {
      &:before {
        content: '#{$i}';
      }
    }
  }
}

这当然会复制 5 份

ul.checkout-bar li:nth-child(1):before {
   content: "1";
}

“内容”正确递增。但我无法让第 n 个子值增加。这在 Sass 中是不可能的吗?

注意 静态 变量可以插值:

$foo: 1;
    &:nth-child(#{$foo}) {
      &:before {
        content: '1';
      }
    }

这很好用。这是我尝试的第一件事。

但是,当在for 循环中使用$i 时,它不起作用。

【问题讨论】:

  • 它不是重复的。那是指对变量的一次使用。我的问题是关于 FOR 循环中的自动递增变量。您链接上的答案不起作用,我已经尝试过了。
  • 考虑到您甚至没有在选择器中引用变量,我想说您还没有尝试过。此外,您声称获得的输出无法从提供的代码中获得。
  • codepen.io/smlombardi/pen/LVPMzG?editors=110 有输出,证明给你我“试过了”
  • 我可能在某个地方打错字了,我发誓我在 sassmeister 中尝试过的前 5 次都出错了。感谢您的帮助。

标签: variables for-loop sass


【解决方案1】:

您需要将$i 包装为:nth-child() 中的整数,如下所示:

$show-numbers: true;

@if $show-numbers {
  @for $i from 1 through 5 {
    &:nth-child(#{$i}) {
      &:before {
        content: '#{$i}';
      }
    }
  }
}

渲染:

:nth-child(1):before {
    content:'1';
}

:nth-child(2):before {
    content:'2';
}

:nth-child(3):before {
    content:'3';
}

:nth-child(4):before {
    content:'4';
}

:nth-child(5):before {
    content:'5';
}

【讨论】:

  • 请不要回答重复的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 2016-12-17
  • 2017-10-26
  • 2016-11-20
  • 1970-01-01
  • 2019-03-09
相关资源
最近更新 更多