我正在尝试在SASS中创建颜色变量,该颜色变量将根据添加到父元素的类设置嵌套元素的样式

时间:2018-07-20 18:10:37

标签: css sass mixins scss-mixins

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

我创建了一个很小的例子,说明我想在更大范围内实现的目标。每个难度级别都作为一种与之相关的颜色,用于不同的事物,例如字体颜色,边框颜色,背景颜色等。

CodePen

<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;
    }
  }
}

1 个答案:

答案 0 :(得分:0)

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

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

@each $name, $color in $colors {
  .lesson.#{$name} {
    border-color: $color;
    button {
      background: $color;
    }
    p {
      color: $color;
    }
  }
}