Adi
Adi

Reputation: 4022

Sass each loop behaviour in mixin issue

Got a Sass issue which is driving me insane. Basically I have the following Sass code:

$breakpoints: mobile 320px, tablet 760px, desktop 960px;

@mixin setbreakpoint($point) {
    @each $breakpoint in $breakpoints {
      @if $point == #{nth($breakpoint, 1)} {
        @media (min-width: #{nth($breakpoint, 2)}) { @content; }
      }
    }
}

.page-wrap {
  width: 75%;
  @include setbreakpoint(mobile) { content:"mobile"; }
  @include setbreakpoint(tablet) { content:"tablet"; }
  @include setbreakpoint(desktop) { content:"desktop"; }
}

@each $breakpoint in $breakpoints {
    .page-wrap-#{nth($breakpoint, 1)} { content:#{nth($breakpoint, 2)}; }
}

Which outputs the following css:

.page-wrap {
  width: 75%; }
  @media (max-width: 320px) {
    .page-wrap { content: "mobile"; } }
  @media (max-width: 760px) {
    .page-wrap { content: "mobile"; } }
  @media (max-width: 960px) {
    .page-wrap { content: "mobile"; } }
  @media (max-width: 320px) {
    .page-wrap { content: "tablet"; } }
  @media (max-width: 760px) {
    .page-wrap { content: "tablet"; } }
  @media (max-width: 960px) {
    .page-wrap { content: "tablet"; } }
  @media (max-width: 320px) {
    .page-wrap { content: "desktop"; } }
  @media (max-width: 760px) {
    .page-wrap { content: "desktop"; } }
  @media (max-width: 960px) {
    .page-wrap { content: "desktop"; } }

.page-wrap-mobile {
  content: 320px; }

.page-wrap-tablet {
  content: 760px; }

.page-wrap-desktop {
  content: 960px; }

Question is: Why does the mixin each loop produce 9 results where the basic class each loop produces 3?

Upvotes: 1

Views: 488

Answers (1)

cimmanon
cimmanon

Reputation: 68339

It's because of this if statement right here:

@if $point == #{nth($breakpoint, 1)} {
    @media (min-width: #{nth($breakpoint, 2)}) { @content; }
}

You're comparing variables with different types. For whatever reason, the compiler always thinks they're equal. All you have to do is remove the string interpolation and it works as you expect:

@if $point == nth($breakpoint, 1) {
    // You don't need when displaying the value either...
    @media (min-width: nth($breakpoint, 2)) { @content; }
}

Upvotes: 2

Related Questions