kizoso
kizoso

Reputation: 1246

In SASS, can I define property as argument in mixin?

I would like to write something like this:

$widthXl: 1000px
$widthSm: 500px
@mixin med ($prop, $xl, $sm)
  @media (max-width: $widthXl)
    &
      $prop: $xl
  @media (max-width: $widthSm)
    &
      $prop: $sm
a
  @include med(width, 600px, 300px)
b
  @include med(color, #000, #888)

And get this:

@media (max-width: 1000px) {
  a {width: 600px}
  b {color: #000}
}
@media (max-width: 500px) {
  a {width: 300px}
  b {color: #888}
}

But my code doesn't compile it. Is it possible?

It would be interesting to know whether someone faced the same problem.


If I remove property, code works fine. But I want to create complex solution.

Upvotes: 3

Views: 156

Answers (1)

René
René

Reputation: 6176

You can use variable "interpolation" like #{$prop}.

My code sample is in scss instead of sass, I like braces. It should compile the same.

$widthXl: 1000px;
$widthSm: 500px;

@mixin med ($prop, $xl, $sm) {
    @media (max-width: $widthXl) {
        & {
            #{$prop}: $xl;
        }
    }
    @media (max-width: $widthSm) {
        & {
            #{$prop}: $sm
        }
    }
}
body {
    @include med(color, red, blue)
}

Some information can be found in the docs

Upvotes: 7

Related Questions