如何用 LESS 创建 10 CSS 类,每个都有 10% 的深灰色背景?

How to create 10 CSS classes, each having 10% darker gray background with LESS?

我正在尝试找出创建 10 个 类 的正确语法,每个都有越来越深的灰色背景颜色。输出可能是这样的:

.bg-gray-1 {
  background-color: #eee;
}
.bg-gray-2 {
  background-color: #ddd; // for example
}
...
.bg-gray-10 {
  background-color: #222; // for example
}

到目前为止,我已经尝试过类似的方法,但在颜色位置打印了 NaNNaNNaN。

// helper class, will never show up in resulting css
// will be called as long the index is above 0
.loop (@index) when (@index > 0) {

    // create the actual css selector
        // use (~'.@{class}_@{index}') for LESS version < 1.4
    .bg-gray-@{index} {
        background-color: darken(#eee, (@index*10)%);
    }

    // next iteration
    .loop(@index - 1);
}

// end the loop when index is 0
.loop (0) {}

.loop(10);

也许是在尝试这样的事情,不久前我在一个使用“50 度灰度”的演示中看到了它。

HTML

    <div class="shades">
      <div class="shade">1<span> Shades of Grey</span></div>
      <div class="shade">2<span> Shades of Grey</span></div>
      <div class="shade">3<span> Shades of Grey</span></div>
      <div class="shade">4<span> Shades of Grey</span></div>
      <div class="shade">5<span> Shades of Grey</span></div>
      <div class="shade">6<span> Shades of Grey</span></div>
      <div class="shade">7<span> Shades of Grey</span></div>
      <div class="shade">8<span> Shades of Grey</span></div>
      <div class="shade">9<span> Shades of Grey</span></div>
      <div class="shade">10<span> Shades of Grey</span></div>
</div>

HTML (翡翠)

- var i = 1
.shades
  while i <= 50
   div.shade= i++
     span  Shades of Grey

正常CSS

.shade {
  color: white;
  padding: 50px;
  text-align: center;
  float: left;
  margin: 5px;
  font-size: 0.8em;
  font-weight: bold;
  width: 10%;
}

.shades div:nth-of-type(1) {
  background-color: #7e7e7e;
}

.shades div:nth-of-type(2) {
  background-color: #7c7c7c;
}

.shades div:nth-of-type(3) {
  background-color: #7a7a7a;
}

.shades div:nth-of-type(4) {
  background-color: #787878;
}

.shades div:nth-of-type(5) {
  background-color: #767676;
}

.shades div:nth-of-type(6) {
  background-color: #747474;
}

.shades div:nth-of-type(7) {
  background-color: #727272;
}

.shades div:nth-of-type(8) {
  background-color: #707070;
}

.shades div:nth-of-type(9) {
  background-color: #6e6e6e;
}

.shades div:nth-of-type(10) {
  background-color: #6c6c6c;
}

SASS

.shade
  color: white
  padding: 50px
  text-align: center
  float: left
  margin: 5px
  font-size: 0.8em
  font-weight: bold
  width: 10%

@for $i from 1 through 50
  .shades
    div:nth-of-type(#{$i})
      background-color: darken(grey, 0.8% * $i)

编辑: 忘记了 source:

问题在于将百分比附加到计算数字的方式。这不会将百分比值输出为数字百分比(如 10%、20% 等),因此 darken() 函数 returns #NaNNaNNaN 作为输出。

.bg-gray-@{index} {
    background-color: darken(#eee, (@index * 10)%);
}

相反,您应该将 % 添加到数字本身,这将使 Less 以百分比形式输出值(而不是字符串或其他内容)。

.bg-gray-@{index} {
    background-color: darken(#eee, (@index * 10%));
}