0

从样式的角度来看,我可以实现我所需要的,但感觉就像我在复制很多代码。

我创建了一个非常小的示例,说明我正在尝试在更大范围内实现的目标。每个难度级别作为与其相关的颜色,用于不同的事物,如字体颜色、边框颜色、背景颜色等。

代码笔

<div class="lesson easy">
  <h2>Easy Lesson</h2>
  <p>Description</p>
  <button>More Info</button>
</div>

<div class="lesson medium">
  <h2>Medium Lesson</h2>
  <p>Description</p>
  <button>More Info</button>
</div>

<div class="lesson hard">
  <h2>Hard Lesson</h2>
  <p>Description</p>
  <button>More Info</button>
</div>

//variables that relate to a specific difficulty
$easy: green;
$medium: orange;
$hard: red;

//base styles
.lesson {
  border: 2px solid black;
  width: 200px;
  float: left;
  margin-right: 10px;
  padding: 0px 20px 20px 20px;
}

button {
  border: 0;
  padding: 10px;
}

//specific styles, is there an easier, cleaner way to write this using a mixin that will allow me to use it on a much larger scale with even more nested HTML elements?
.lesson {
  &.easy {
    border-color: $easy;
    button {
      background: $easy;
    }
    p {
      color: $easy;
    }
  }
  &.medium {
    border-color: $medium;
    button {
      background: $medium;
    }
    p {
      color: $medium;
    }
  }
  &.hard {
    border-color: $hard;
    button {
      background: $hard;
    }
    p {
      color: $hard;
    }
  }
}
4

1 回答 1

0

您可以在地图上编写所有变体并迭代其属性以生成所有类组合。

$colors: (
  'easy': green,
  'medium': orange,
  'hard': red
);

@each $name, $color in $colors {
  .lesson.#{$name} {
    border-color: $color;
    button {
      background: $color;
    }
    p {
      color: $color;
    }
  }
}
于 2018-07-21T18:19:34.683 回答