realph
realph

Reputation: 4671

Access @mixin variable outside of @mixin

So I've got a @mixinthat lets me define my logo width and gives me an automatic height based on the ratio of my logo image.

@mixin m-logoSize($width) {
  width: $width;
  height: floor($width / 4.72727272727273);
}

I'm trying to find out if there's a way for me to access the $width variable, so I can assign it to a different property like so.

// sass

.logo {
  @include m-logoSize(300px);
  background-size: $width $height;
}

// translates to this css

.logo {
  width: 300px;
  height: 63px;
  background-size: 300px 63px;
}

Is there any wizardry that makes this possible. Any help is appreciated.

Thanks in advance!

Upvotes: 1

Views: 1377

Answers (1)

Colin Bacon
Colin Bacon

Reputation: 15609

I think you are better off setting global variables for these two values, then you can reach them anywhere.

Example

// Global variables
$logo-width: 0 !default;
$logo-height: floor($logo-width / 4.72727272727273) !default;

// Mixin
@mixin m-logoSize() {  
  width: $logo-width;
  height: $logo-height;
}

// Sass
$logo-width: 300px;

.logo {
  @include m-logoSize();
  background-size: $logo-width $logo-height;
}

Update

To change the value at different breakpoints you would just set the variable in the scope of the media query.

Responsive Example

.logo {
  @media screen and (max-width: 600px) {
      $logo-width: 150px;
      @include m-logoSize();
      background-size: $logo-width $logo-height;
  }

  @media screen and (min-width: 601px) {
      $logo-width: 300px;
      @include m-logoSize();
      background-size: $logo-width $logo-height;
  }
}

Upvotes: 2

Related Questions