如何在sass中编写媒体查询?

How to write media queries in sass?

我试图找出在 sass 中编写媒体查询的方法。这是我的代码

devices: ("sphone","phone","tablet")
$breakpoints: ( width2: ('sphone' : 320, 'phone' : 360, 'tablet' : 600), height2: ('sphone' : 509, 'phone' : 583, 'tablet' : 952))

=screen-width($device)
  @each $name in $devices
    @if $device != $name
      @error "No device of such name"
  $media: (max-width: map-get(map-get($breakpoints,"width2"),$device) + px )
  @media screen only and ($media)
    @content
  
  
.hello
  background: #333
  @include screen-width("mobile")
    background: #444
    

我正在尝试在 sass 中编译相同的内容,但它一直向我抛出以下错误。不知道为什么。

Properties are only allowed within rules, directives, mixin includes, or other properties.

有什么见解吗?

您的代码中有一些错误,缺少 $devices 变量中的 $。您写 @include screen-width("mobile") 但手机不在设备列表中。在 $media 中,变量 max-width 必须是一个字符串,然后你必须使用插值来添加在 @media 规则中。

@each循环中的比较错误,暂时不解决。此代码有效:

$devices: ("sphone","phone","tablet")
$breakpoints: ( width2: ('sphone' : 320, 'phone' : 360, 'tablet' : 600), height2: ('sphone' : 509, 'phone' : 583, 'tablet' : 952))

=screen-width($device)
  $media: "max-width:" map-get(map-get($breakpoints,"width2"),$device) + px
  @media screen only and (#{$media})
    @content

.hello
  background: #333
  @include screen-width("sphone")
    background: #444