是否可以在不使用mixins的情况下避免重复属性?

时间:2019-06-24 18:04:16

标签: css sass

如何避免属性重复?

我用颜色作为参数创建了一个mixin(这是唯一更改的属性)。是否有另一种方法可以不使用mixins来进行重构?

td.animal-table__cell {
  &.animalType {
    &.mammal span::before {
      content: ' ';
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background-color: red;
    }

    &.reptile span::before {
      content: ' ';
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background-color: green;
    }

    &.bird span::before {
      content: ' ';
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background-color: purple;
    }

    &.others span::before {
      content: ' ';
      width: 6px;
      height: 6px;
      border-radius: 3px;
      background-color: orange;
    }
  }
}

1 个答案:

答案 0 :(得分:3)

用逗号枚举以分组常用样式:

td.animal-table__cell {
    &.animalType {
        &.mammal, &.reptile, &.bird, &.others {
            span::before {
                content: ' ';
                width: 6px;
                height: 6px;
                border-radius: 3px;
            }
        }
        &.mammal span::before {
            background-color: red;
        }
        &.reptile span::before {
            background-color: green;
        }
        &.bird span::before {
            background-color: purple;
        }
        &.others span::before {
            background-color: orange;
        }
    }
}

如果您知道无论哪种方式,嵌套样式都将具有这些样式,则甚至可以删除列表并将span::before直接放入&.animalType