使用Sass从媒体查询中扩展选择器 [英] Extending selectors from within media queries with Sass

查看:958
本文介绍了使用Sass从媒体查询中扩展选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目类和一个紧凑的修饰符类:

I have an item class and a compact "modifier" class:

.item { ... }
.item.compact { /* styles to make .item smaller */ }

但是,我想添加一个 @media 查询,强制 .item 类在屏幕

This is fine. However, I'd like to add a @media query that forces the .item class to be compact when the screen is small enough.

首先想,这是我想做的:

On first thought, this is what I tried to do:

.item { ... }
.item.compact { ... }
@media (max-width: 600px) {
  .item { @extend .item.compact; }
}

但这会产生以下错误:


您不能在@media内@extend外部选择器。您可以在同一个指令中只有
@extend选择器。

You may not @extend an outer selector from within @media. You may only @extend selectors within the same directive.

如何使用SASS完成此操作,复制/粘贴样式?

How would I accomplish this using SASS without having to resort to copy/pasting styles?

推荐答案

简单的答案是:你不能因为Sass不能(或不会)组成它的选择器。您不能在媒体查询内,也不能扩展媒体查询以外的内容。它肯定会很好,如果它会简单地拿一个它的副本,而不是试图编写选择器。

The simple answer is: you can't because Sass can't (or won't) compose the selector for it. You can't be inside of a media query and extend something that's outside of a media query. It certainly would be nice if it would simply take a copy of it instead of trying to compose the selectors. But it doesn't so you can't.

如果你有一个case你将在媒体查询内部和外部重用一段代码,并且仍然希望它能够扩展它,然后同时编写一个mixin和一个extend类:

If you have a case where you're going to be reusing a block of code inside and outside of media queries and still want it to be able to extend it, then write both a mixin and an extend class:

@mixin foo {
    // do stuff
}

%foo {
    @include foo;
}

// usage
.foo {
    @extend %foo;
}

@media (min-width: 30em) {
    .bar {
        @include foo;
    }
}



在外部媒体查询中扩展选择器



这不会真正帮助您的用例,但它是另一个选项:

Extend the selector within a media query from the outside

This won't really help your use case, but it is another option:

%foo {
  @media (min-width: 20em) {
    color: red;
  }
}

@media (min-width: 30em) {
  %bar {
    background: yellow;
  }
}

// usage
.foo {
  @extend %foo;
}

.bar {
  @extend %bar;
}



等待,直到Sass解除此限制(或自行修补)



有很多关于这个问题的讨论(请不要对这些线程做出贡献,除非你有一些有意义的添加:维护者已经知道用户希望这个功能,它只是一个如何实现它的问题和语法应该是什么)。

Wait until Sass lifts this restriction (or patch it yourself)

There are a number of ongoing discussions regarding this issue (please don't contribute to these threads unless you have something meaningful to add: the maintainers are already aware that users desire this functionality, it's just a question of how to implement it and what the syntax should be).

  • https://github.com/sass/sass/issues/1050
  • https://github.com/sass/sass/issues/456

这篇关于使用Sass从媒体查询中扩展选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆