AJP
AJP

Reputation: 28473

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?

Upvotes: 0

Views: 117

Answers (1)

cimmanon
cimmanon

Reputation: 68319

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

Upvotes: 1

Related Questions