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

CSS

蛋蛋猿

2020-03-24

是否可以写像

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

这样我们就可以在一个类中定义桌面和移动CSS

我已经尝试过了,但是似乎没有用

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

第3717篇《CSS:在一个类中定义媒体查询》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
卡卡西 2020.03.24

有用:

.column-1-3 {
  width: 33.3333%;
  @media (max-width: 600px) {
    width: 100%;
  }
}

http://css-tricks.com/media-queries-sass-3-2-and-codekit/

樱小胖Mandy 2020.03.24

在纯CSS中,答案是否定的。 你不能 媒体查询应始终是外壳,并封装要在该条件下应用的内部。

但是,在SASS和LESS中,它是完全有效的。 任何支持嵌套大括号的转换器都应该能够将媒体查询移至外部,因此允许CSS按照上述方式工作。(您可以在编译sass / less文件之后检查输出CSS并查看它们执行此操作。)

因此,如果您有这样的事情:

body {
    background:green;
    @media (min-width:1000px) {background:red;}
}

在CSS中,屏幕将变为绿色(因为它忽略了体式定义块中的怪异@media事物),而在SASS / LESS中,则变为红色(因为它获得了您实际想要看到的内容)。

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

body {
  background: green;
}
@media (min-width: 1000px) {
  body {
    background: red;
  }
}
小胖Gil 2020.03.24

您应该这样做:

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

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

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

我只是注意到您正在使用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 */
    } 
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android