Rudraprasad Das Rudraprasad Das - 1 month ago 21
Sass (Sass) Question

How to write media queries in sass?

I was trying to figure out ways to write media queries in sass. This is my code



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





I am trying to compile the same in sass but it keeps on throwing me the following error. I don't know why.

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


Any insights?

Answer

You have some errors in your code, missing the $ in $devices variable. You write @include screen-width("mobile") but mobile isn't in devices list. In $media variable max-width must be a string and then you have to use interpolation to add in the @media rule.

The comparision in the @each loop is wrong but I don't solve this for the moment. This code works:

$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
Comments