在SASS中有没有办法在可扩展选择器中引用选择器值?

时间:2016-10-25 06:41:58

标签: html css sass

在SASS中,我想为按钮设置悬停焦点伪类,以使用选择器内按钮的正常颜色扩展%mybutton - 这样我就不必为每种类型的按钮声明它。基本上我想知道某种方式来引用“孩子”。将以抽象方式继承此选择器的选择器。

例如:

%mybutton {
  padding: 6px 20px;
  border-radius: 2px;

  &:hover, &:focus {
    color: <use selectors color>;
    outline: none;
  }
}

button.btn-white {
  @extend: %mybutton;
  background-color: white;
  color: black;
}

button.btn-blue {
  @extend: %mybutton;
  background-color: blue;
  color: white;
}

这有可能吗?

1 个答案:

答案 0 :(得分:1)

是的,虽然Sass的@mixin函数应该可以实现。 [Sass Documentation #mixin] 我使用类似的构造来构建我的类并通过例如扩展它们来扩展它们。过渡前缀。可以采用相同的规则/构造来构建您自己的&#34;带变量实现的规则。

我一直都是&#34;核心&#34;文件夹,包括我的mixin函数和变量。 在这个例子中,我向您展示了函数&#34; vendor-prefix&#34;和&#34;占位符&#34;。对于您的解决方案,请在下面进一步了解。

我的例子

/* Vendor Prefixes */
@mixin vendor-prefix($name, $argument) {
  -webkit-#{$name}: #{$argument};
  -ms-#{$name}: #{$argument};
  -moz-#{$name}: #{$argument};
  -o-#{$name}: #{$argument};
  #{$name}: #{$argument};
}


/* Placeholder */
@mixin placeholder {
  &::-webkit-input-placeholder {@content}
  &:-moz-placeholder           {@content}
  &::-moz-placeholder          {@content}
  &:-ms-input-placeholder      {@content}
}

/* Your new Function to extend the hover, focus statements */
@mixin button-effects($color_on_hover){
     &:hover, &:focus {
         color: #{$color_on_hover);  
     }
}


To use them in a class, you can do the following.
.your_class {
   display:block; width:20px; height:20px;
   @include('transition', 'all .3s');
}

您案件的解决方案

我已经编辑了一下,因此该功能提供了默认颜色,悬停颜色和背景颜色的3个参数。我认为这在您尝试完成的大多数用例中都很有用。

// Your Mixin function for extension
// @param   $color_default      Default Color state of your Button
// @param   $color_on_hover     Color on hovering your element
// @param   $background_color   Background Color of your Button element (in case of you need)
@mixin btn_build($color_default, $color_on_hover, $background_color){
    padding: 6px 20px;
    border-radius: 2px;
    color: #{$color_default};
    background-color: #{$background_color};

    &:hover, &:focus {
      color: #{$color_on_hover};
      outline: none;
    }
}


// Button base class
.button {
   display:inline-block;
   height:34px; line-height:34px;
}

// Button white
.button.btn-white {
    @include btn_build('black', 'red', 'white');
}

// Button blue
.button.btn-blue {
    @include btn_build('black', 'white', 'blue');
}

编译示例代码

实际上没有压缩,使其有点可读。 默认情况下,如果您编译,您可以使用压缩。例如。使用ruby sass编译器我使用它:

  

sass - watch source:dist --style = compressed

.button {
  display: inline-block;
  height: 34px;
  line-height: 34px; }

.button.btn-white {
  padding: 6px 20px;
  border-radius: 2px;
  color: black;
  background-color: white; }
  .button.btn-white:hover, .button.btn-white:focus {
    color: red;
    outline: none; }

.button.btn-blue {
  padding: 6px 20px;
  border-radius: 2px;
  color: black;
  background-color: blue; }
  .button.btn-blue:hover, .button.btn-blue:focus {
    color: white;
    outline: none; }
相关问题