Matúš Rebroš
Matúš Rebroš

Reputation: 145

SASS: @extend inside of @media query

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?

Upvotes: 6

Views: 598

Answers (2)

Scipion
Scipion

Reputation: 11888

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

Upvotes: 3

scooterlord
scooterlord

Reputation: 15349

...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;
  }
}

Upvotes: 2

Related Questions