1
votes

This is one for the SCSS pros. I want to extend a selector within a media query. I'm not "leaving" the scope, the selector and the line where I extend are in the same media query.

However, I use the selector that I want to extend in another media query as well and that gives me an error, when I extend it.

I don't know if I explained it well, but you might get it from my code:

Partial File _tablet.scss

@media (min-width: 769px) {

  .font-family {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
  }

  body {
    @extend .font-family;
  }

}

Partial file _desktop.scss

@media (min-width: 992px) {

  .font-family {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
  }

  body {
    @extend .font-family;
  }

}

This gives me the following error:

You may not @extend an outer selector from within @media. You may only @extend selectors within the same directive. From "@extend .font-family" on line 8 of _desktop.scss

I know that you can't extent an outer selector from within @media, but that's not what I'm trying to do here.

When I leave one of the above files out, it works. So somehow SASS thinks that I want to select a selector from the other media query, which I don't. Am I doing something wrong here? How do you extend selectors that are being used in multiple media queries?

2

2 Answers

0
votes

Try to inheritance by extending a parent (placeholder) selector. You can read more in this link.

  %font-family {
    font-family: 'Lato', Helvetica, Arial, sans-serif;
  }

  .font-family, body {
    @extend %font-family
  }
0
votes

You can move your body declaration outside the media queries, even if the thing it extends only exists within the media queries.

for example, this:

body {
  @extend .font-family;
}
@media (min-width: 769px) {
  .font-family {
    font-family: Helvetica, Arial, sans-serif;
  }
}
@media (min-width: 888px) {
  .font-family {
    font-family: Arial, sans-serif;
  }
}

will compile to this:

@media (min-width: 769px) {
  .font-family, body {
    font-family: Helvetica, Arial, sans-serif;
  }
}
@media (min-width: 888px) {
  .font-family, body {
    font-family: Arial, sans-serif;
  }
}