【问题标题】:SASS function to iterate nth-child(n+1) and lighten/darken($color, 5n%)SASS 函数迭代 nth-child(n+1) 和变亮/变暗($color, 5n%)
【发布时间】:2018-12-01 03:16:50
【问题描述】:

我使用了很多 SASS/SCSS,但通常不使用 complex 任何函数。我目前的需求似乎是一个函数的完美用例,但不确定如何在 SASS/SCSS 中像这样循环。

我需要一个阶梯式颜色模式来更改每个附加列表项的背景颜色。

我需要用各种基色重复这个任务,我希望有人能提供一个简洁的 SASS/SCSS 函数来替换这个 SCSS 块,它将 li:nth-child() 增加 1 (n+1) 和每个li 增加background-color: lighten($color, 5%) 5% (5n)。

.service {
  background-color: $color;

  .list {
    li:nth-child(2) {
      background-color: lighten($color,5%);
    }
    li:nth-child(3) {
      background-color: lighten($color,10%);
    }
    li:nth-child(4) {
      background-color: lighten($color,15%);
    }
    li:nth-child(5) {
      background-color: lighten($color,20%);
    }
    li:nth-child(6) {
      background-color: lighten($color,25%);
    }
    li:nth-child(7) {
      background-color: lighten($color,30%);
    }
  }
}

如果需要任何说明,请告诉我。非常感谢您的帮助和建议。

【问题讨论】:

    标签: css function sass scss-mixins


    【解决方案1】:

    试试这个:

    $colors: lighten(red, 5%), lighten(red, 10%), lighten(red, 15%), lighten(red, 20%);
    
    @each $color in $colors {
        $i: index($colors, $color);
        li:nth-child(#{$i}) {
            background-color: nth($color, 1);
        }
    }
    

    输出如下:

    li:nth-child(1) {
        background-color: #ff1a1a;
    }
    
    li:nth-child(2) {
        background-color: #ff3333;
    }
    
    li:nth-child(3) {
        background-color: #ff4d4d;
    }
    
    li:nth-child(4) {
        background-color: #ff6666;
    }
    

    【讨论】:

      【解决方案2】:

      我觉得你可以试试:

      @for $i from 2 through 7 {
        li:nth-child(#{$i}) {
            background-color: lighten($color, ($i - 1) * 5%);
        }
      }
      

      【讨论】:

        【解决方案3】:

        尝试以下方法:

        $alpha: 5;
        $color: red;
        @for $i from 1 through 4 {
            li:nth-child(#{$i}) {
                background-color: lighten($color, $alpha + 0%);
            }
        
            $alpha: $alpha + 5;
        }
        

        输出:

        li:nth-child(1) {
          background-color: #ff1a1a;
        }
        
        li:nth-child(2) {
          background-color: #ff3333;
        }
        
        li:nth-child(3) {
          background-color: #ff4d4d;
        }
        
        li:nth-child(4) {
          background-color: #ff6666;
        }
        

        您可以将 fromtrough 的值更改为 2 和 7 或最适合您的值。

        【讨论】:

        • 谢谢。您的回答也有效果,但选择了更简洁的解决方案。
        猜你喜欢
        • 2012-09-23
        • 2020-04-04
        • 1970-01-01
        • 2013-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        相关资源
        最近更新 更多