CSS:在一个类中定义媒体查询

cqc*_*991 13 css sass

有可能写出类似的东西

.global-container
  margin-top: 60px
  background-image: $image-bg
  @media(max-width: 767px)
    margin-top: 0
    background-image: none
Run Code Online (Sandbox Code Playgroud)

所以我们可以在一个类中定义桌面和移动css

我试过这个,但似乎没有用

更新:这实际上有效:http: //css-tricks.com/media-queries-sass-3-2-and-codekit/

Fel*_*lix 17

你应该这样做:

@media all and (max-width: 767px) {
    .global-container {
        margin-top: 0;
        background-image: none;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要定位桌面,可以使用:

@media (min-width:1025px) { 
    .global-container {
        margin-top: 0;
        background-image: none;
    }
}
Run Code Online (Sandbox Code Playgroud)

我只是注意到你正在使用SASS,你可以这样做:

.global-container {
    margin-top: 60px;
    background-image: $image-bg;
    @media (max-width: 767px) {
        /* Your mobile styles here */
    }
    @media (min-width:1025px) {
        /* Your desktop styles here */
    } 
}
Run Code Online (Sandbox Code Playgroud)


dke*_*ner 10

在简单的CSS中,答案是否定的. 你不能.媒体查询应该始终是外壳,包含要在该条件下应用的内部.

然而,在SASS和LESS中,它完全有效. 任何支持嵌套大括号的转换器都应该能够将媒体查询移动到外部,因此允许CSS如上所述工作.(您可以在编译sass/less文件后检查输出CSS并查看它们.)

所以,如果你有这样的事情:

body {
    background:green;
    @media (min-width:1000px) {background:red;}
}
Run Code Online (Sandbox Code Playgroud)

CSS中的屏幕将是绿色的(因为它忽略了体型定义块内部那种奇怪的@media事物)而SASS/LESS中则显示为红色(因为它得到了你真正喜欢看到的内容).

确切地说,预处理器会将上面的代码段理解为:

body {
  background: green;
}
@media (min-width: 1000px) {
  body {
    background: red;
  }
}
Run Code Online (Sandbox Code Playgroud)