根据 CSS class 更改 SCSS 变量

Change a SCSS Variable based on CSS class

我有一系列 a 标签组成一个网格(每个 a 是一个带有 class .portfolio-grid-item 的块)。

每个 .portfolio-grid-item 包含多个 divheading 元素,并通过变量 ($grid-color: $blue;) 使用默认颜色。

我正在尝试创建将执行以下操作的 SCSS 规则:

例如

class编辑为 .portfolio-grid-item .orange 的元素应该用 $grid-color: $orange;

替换 $grid-color: $blue

我试过使用 mixinif 语句,但我以前从未这样做过,我不确定该方法是否正确或受支持。

我的笔在这里:http://codepen.io/anon/pen/EjwarE

如有任何建议,我们将不胜感激!

更新:

用一些简单的术语来说(我知道这不是真正的代码,这只是我的目标逻辑,希望这有帮助!):

// Default
$grid-color: $blue


// Statement
if HTML element has class = `.orange`

// Change the following variable
$grid-color: $orange

想法是这将一次性覆盖 all 个 $grid-color 实例

嗯,你可以这样做:

@mixin gridbg($bg) {
   @if $bg == blue {
   background: $blue;
 } @else if $bg == green {
   background: $green;
 } @else if $bg == orange {
   background: $orange;
 }
}

.orange {
  @include gridbg(orange);
}

.green {
  @include gridbg(green);
}

.blue {
  @include gridbg(blue);
}

更新

上面只是一个简单的例子,但是你可以用 mixins 做更多的事情: 这是预览:

.orange {
    @include gridbg(orange);
    h3 {
      color: $grid-color
    }
    h5 {
      color: white;
      background: $orange;
    }
    &:hover {
        @include gridbghover(orange);
        h3 {
          color: $grid-color
        }
        h5 {
          color: white;
          background: darken($orange, 20%);
        }
    }
}

还有一个demo

这可能更符合您的需要。我确信它可以改进,但我使用了一个颜色值图,我循环通过它来生成你的颜色变体。

我没有使用 if 语句纯粹是因为默认情况下我修改了您的主要元素 CSS 以包含标准的蓝色背景。通过这种方式,我们的循环只需要产生额外的映射颜色,并且通过添加到该元素的额外 class 覆盖样式。

SCSS:

//set your base colours
$colors: (
  green: green,
  blue: blue,
  orange: orange
);

//loop through your map and apply colours to the mapped values. This overrides the default where the additional class is applied. 
@each $colors, $specific in $colors {
  .portfolio-grid-item.#{$colors} {
    background: $specific;
  }
}

您的投资组合项目:

// Gird Sizings
.portfolio-grid-item {
  height: $grid-item-height;   
  position: relative;
  text-decoration: none;
  float: left;
  width: 33.33%;
  //set default
  background: $grid-color;
}

工作示例 - Codepen

使用此方法,您可以通过调整地图以包含更多值来将颜色应用于字体等。例如,您可以在地图中同时映射背景和字体颜色。如:

//set your base colours
$colors: 
  (green, white, green),
  (orange, white, orange);

//loop through your map and apply colours to the mapped values. This overrides the default where the additional class is applied. 
@each $color, $text, $bg in $colors {
  .portfolio-grid-item.#{$color} {
    background: $bg;
    color: $text;
  }
}

然后您可以将悬停添加到循环中,并根据需要使映射到 $bg 的背景变暗。据我了解,这应该可以达到预期的效果。