【问题标题】:Sass/Compass - passing a variable to a nested background-image mixinSass/Compass - 将变量传递给嵌套的背景图像混合
【发布时间】:2013-12-14 00:35:25
【问题描述】:

我正在尝试将变量(颜色十六进制代码)传递给我已嵌套在我已声明的 mixin 中的 Compass 背景图像 mixin。

当 Compass 尝试编译 CSS 时,它会抛出以下错误。

error sass/styles.scss (Line 103 of sass/_mixins.scss: Expected a color. Got: #fef1d0)

当我在 background-image mixin 中用硬编码的十六进制值(即#FEF1D0)替换变量时,CSS 编译不会出错。

下面是代码。

// The variables
  // primary
  $yellow:           #FCB813;
  $blue:             #005696;

  // secondary
  $yellow-soft:       #FEF1D0;
  $blue-soft:         #D9E6EF;

// The mixin
  @mixin main-menu($primary, $secondary) {
      border-bottom: {
        color: $primary;
      style: solid;
    }
    background: #fff; // older browsers.
    @include background-image(linear-gradient(top, white 50%, $secondary 50%));
    background-size: 100% 200%;
    background-position: top;
    margin-left:10px;
    @include transition(all 0.5s ease);
    &:hover {
      background-position: bottom;
    }
  }

//Using the mixin
  #main-menu {
    $sections: (
      yellow $yellow $yellow-soft,
      blue $blue $blue-soft
      );
    @each $color in $sections {
      a.#{nth($color, 1)} {
        @include main-menu(#{nth($color, 2)}, #{nth($color, 3)});
      }
    }

$secondary 在 background-image mixin 中被 #FEF1D0 替换时编译的 CSS。 即@include background-image(linear-gradient(top, white 50%, #FEF1D0 50%));

#main-menu a.yellow {
  border-bottom-color: #fcb813;
  border-bottom-width: 3px;
  border-bottom-style: solid;
  background: #fff;
  background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(50%, #ffffff), color-stop(50%, #fef1d0));
  background-image: -webkit-linear-gradient(top, #ffffff 50%, #fef1d0 50%);
  background-image: -moz-linear-gradient(top, #ffffff 50%, #fef1d0 50%);
  background-image: -o-linear-gradient(top, #ffffff 50%, #fef1d0 50%);
  background-image: linear-gradient(top, #ffffff 50%, #fef1d0 50%);
  background-size: 100% 200%;
  background-position: top;
  margin-left: 10px;
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;
}

我们的目标是在悬停状态下进行背景过渡,通过 bg-color 从底部到顶部的滑动过渡填充链接背景,这要感谢这个伟大的 suggestion。除了 compass 解析变量的方式之外,它的效果非常好。

【问题讨论】:

    标签: html css sass background-image compass-sass


    【解决方案1】:

    问题出在@include 参数中。您对两个参数都使用 Sass 插值,这会导致 mixin 将这些变量视为字符串,而不是在本例中为颜色:

    type_of(#FEF1D0); // returns color
    type_of(#{#FEF1D0}); // returns string
    

    您可以将字符串传递给color 属性,但linear-gradient 是一个函数,它需要颜色。

    要解决此问题,您应该删除第二个参数的插值以将其作为颜色传递。您可以对第一个参数使用插值,但这是不必要的,因此我建议您将其删除。

    所以你应该使用:

    @include main-menu(nth($color, 2), nth($color, 3));
    

    代替:

    @include main-menu(#{nth($color, 2)}, #{nth($color, 3)})
    

    【讨论】:

    • 感谢您的回答,它解决了我的问题,也提高了我对 SASS 插值的理解。
    猜你喜欢
    • 2011-07-23
    • 2013-08-15
    • 2011-08-16
    • 2012-02-19
    • 2015-11-22
    • 1970-01-01
    • 2012-12-07
    • 2011-02-21
    • 2017-10-30
    相关资源
    最近更新 更多