Home > Article > Web Front-end > How Can You Extend Selectors Within Media Queries in Sass?
Extending Selectors Using Media Queries in Sass
When working with Sass, you often have a need to extend selectors from within media queries. This can be useful for applying different styles to elements based on their size or orientation. However, Sass has a limitation where you cannot extend an outer selector from within a media query.
In the provided code example:
<code class="scss">.item { ... } .item.compact { /* styles to make .item smaller */ } @media (max-width: 600px) { .item { @extend .item.compact; } }</code>
This approach results in an error because Sass cannot compose the selector for you. Specifically, you cannot be inside of a media query and extend something that's outside of it.
Alternative Approaches
Due to this limitation, you have several alternatives:
Using Mixins
Create a mixin and an extend class to reuse code within and outside of media queries:
<code class="scss">@mixin foo { // do stuff } %foo { @include foo; } // usage .foo { @extend %foo; } @media (min-width: 30em) { .bar { @include foo; } }</code>
Extending the Selector from the Outside
While not directly applicable to the given use case, this method allows you to extend a selector within a media query from the outside:
<code class="scss">%foo { @media (min-width: 20em) { color: red; } } @media (min-width: 30em) { %bar { background: yellow; } } // usage .foo { @extend %foo; } .bar { @extend %bar; }</code>
Ongoing Discussions
There are active discussions regarding this limitation in the Sass community. Users have expressed a desire for this functionality, and the maintainers are considering ways to implement it effectively. However, no definitive solution has been reached yet.
The above is the detailed content of How Can You Extend Selectors Within Media Queries in Sass?. For more information, please follow other related articles on the PHP Chinese website!