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

How Can You Extend Selectors Within Media Queries in Sass?

Barbara Streisand
Release: 2024-11-02 03:42:30
Original
943 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template