4

I have simple code with SCSS code where is @extend within @media query.

SCSS complier gives me error on both of this variations:

VARIATION 1:

%dark-theme {
    background: $dark-background;
}

%light-theme {
    background: $light-background;
}

@media (prefers-color-scheme: light) {
    body {
        @extend %light-theme;
    }
}

@media (prefers-color-scheme: dark) {
    body {
        @extend %dark-theme;
    }
}

VARIATION 2

%dark-theme {
    background: $dark-background;
}

%light-theme {
    background: $light-background;
}

@media (prefers-color-scheme: light) {
    @extend %light-theme;
}

@media (prefers-color-scheme: dark) {
    @extend %dark-theme;
}

Is there any solution how I can do the @extend in basic element and also in @media query?

Matúš Rebroš
  • 115
  • 1
  • 9
  • 2
    This may help answer your question: https://stackoverflow.com/questions/14840918/extending-selectors-from-within-media-queries-with-sass – Rehan Butt Oct 08 '21 at 02:25

2 Answers2

2

You cannot use @extend inside a media query. What you can do it the other way around though, use the media query inside the class you are extending.

%dark-theme {
    @media (prefers-color-scheme: dark) {
        background: $dark-background;
    }
}

%light-theme {
    @media (prefers-color-scheme: light) {
        background: $light-background;
    }
}

body {
    @extend %light-theme;
    @extend %dark-theme;
}

mixin is also an alternative

Scipion
  • 11,449
  • 19
  • 74
  • 139
2

...or you can simply use mixins:

@mixin dark-theme {
    background: $dark-background;
}

@mixin light-theme {
    background: $light-background;
}

@media (prefers-color-scheme: light) {
   body {
    @include light-theme;
   }
}

@media (prefers-color-scheme: dark) {
  body {
    @include dark-theme;
  }
}
scooterlord
  • 15,124
  • 11
  • 49
  • 68