简体   繁体   中英

Sass mixin to apply to class

The following Sass:

@mixin colourCount
  .one
    background: rgba(0, 160, 0, 0.5)
  .two
    background: rgba(255, 255, 0, 0.6)

.count
  @include colourCount

.cost
  @include colourCount

Produces the CSS:

.count .one {
  background: rgba(0, 160, 0, 0.5);
}
.count .two {
  background: rgba(255, 255, 0, 0.6);
}

.cost .one {
  background: rgba(0, 160, 0, 0.5);
}
.cost .two {
  background: rgba(255, 255, 0, 0.6);
}

Is it possible with Sass to reuse the mixin to produce, notice the absence of a space between .cost and .one :

.count .one {
  background: rgba(0, 160, 0, 0.5);
}
.count .two {
  background: rgba(255, 255, 0, 0.6);
}

.cost.one {
  background: rgba(0, 160, 0, 0.5);
}
.cost.two {
  background: rgba(255, 255, 0, 0.6);
}

Something like:

.cost @include colourCount

would be great but obviously doesn't work. Is this possible at all?

You cannot have a mixin that will do both, no. The mixin you would need to generate your second set of code looks like this:

@mixin colourCount {
  &.one {
    background: rgba(0, 160, 0, 0.5)
  }
  &.two {
    background: rgba(255, 255, 0, 0.6)
  }
}

Realistically, you would want to be using @extend for this purpose anyway.

%colours {
  &.one {
    background: rgba(0, 160, 0, 0.5)
  }
  &.two {
    background: rgba(255, 255, 0, 0.6)
  }
}

.foo {
  @extend %colours;
}

.bar {
  .one {
    @extend %colours.one;
  }

  .two {
    @extend %colours.two;
  }
}

Generates:

.one.foo, .bar .one {
  background: rgba(0, 160, 0, 0.5);
}
.two.foo, .bar .two {
  background: rgba(255, 255, 0, 0.6);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM