Home  >  Article  >  Web Front-end  >  How Can You Extend Selectors Within Media Queries in Sass?

How Can You Extend Selectors Within Media Queries in Sass?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 03:42:30868browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn