Search code examples
csssassmedia-queries

Sass : overwrite definitions with different placeholder in @media query


I've got the following scss:

@mixin logo($size:mobile) {

  @if $size == mobile {

    #logo {

      @extend %logoMobile;

      a {

        @extend %logoMobile;

      }

    }

  }
  @else {

    #logo {

      @extend %logoDesktop;

      a {

        @extend %logoDesktop;

      }

    }

  }

}

%fullWidth {
  width: 100%;
}

%logoMobile {
  @extend %fullWidth;
  height: 30px;
}

%logoDesktop {
  width: 211px;
  height: 35px;
}


#header {

  @include logo('mobile');

}

@media only screen and (min-width: 768px) {

  #header {

    @include logo('desktop');

  }

}

The generated css output of which is:

#header #logo, #header #logo a {
  width: 100%;
}

#header #logo, #header #logo a {
  height: 30px;
}

Any idea why the @media query is not generated?


Solution

  • Extending classes from within a media query that exist outside of the media query is not allowed. The console tells you so when you compile the Sass file:

    DEPRECATION WARNING on line 12 of test.scss:
      @extending an outer selector from within @media is deprecated.
      You may only @extend selectors within the same directive.
      This will be an error in Sass 3.3.
      It can only work once @extend is supported natively in the browser.
    
    DEPRECATION WARNING on line 14 of test.scss:
      @extending an outer selector from within @media is deprecated.
      You may only @extend selectors within the same directive.
      This will be an error in Sass 3.3.
      It can only work once @extend is supported natively in the browser.
    

    Unless you're actually reusing your logo styles, this is severely over complicated. Overusing extend can lead to larger CSS files rather than smaller, so use them with care. If you must extend with media queries, this would be the way to do it:

    %logo {
        &, & a {
            width: 100%;
            height: 30px;
        }
    
        @media only screen and (min-width: 768px) {
            &, & a {
                width: 211px;
                height: 35px;
            }
        }
    }
    
    #header {
        #logo {
            @extend %logo;
        }
    }
    

    Output:

    #header #logo, #header #logo a {
      width: 100%;
      height: 30px; }
    @media only screen and (min-width: 768px) {
      #header #logo, #header #logo a {
        width: 211px;
        height: 35px; } }