首页 > 解决方案 > 是否可以在不使用 mixins 的情况下避免属性重复?

问题描述

如何避免属性重复?

我创建了一个以颜色为参数的 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;
    }
  }
}

标签: csssass

解决方案


用逗号枚举来对常用样式进行分组:

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


推荐阅读