SASS媒体查询最佳做法?

时间:2016-09-29 15:04:05

标签: css sass

将媒体查询嵌套在元素中是否可以?如果我想在其他地方使用min-width: 480px,那将会有很大的重复。请看我的代码示例。或者只是用旧的方式?有什么想法吗?

SASS

.navbar {
     height: 500px;
     width: 500px;

     @media screen and (min-width: 480px) {
         background-color: lightgreen;
     }
}

.items {
    padding: 15px;
    color: red;

    @media screen and (min-width: 480px) {
        border: 1px solid black;
    }
}

CSS

@media screen and (min-width: 480px) {
   .navbar {
       background-color: lightgreen;
   }

   .items {
       border: 1px solid black;
   }
}

1 个答案:

答案 0 :(得分:0)

$pc: 1024px;    // PC screen size.
$tablet: 720px; // Tablet screen size.
$phone: 320px;  // Phone screen size.

@mixin responsive($media) {
  @if $media= phone {
    @media only screen and (max-width: $tablet - 1) {
      @content;
    }
  }
  @else if $media= tablet {
    @media only screen and (min-width: $tablet - 1) and (max-width: $pc) {
      @content;
    }
  }
  @else if $media= pc {
    @media only screen and (min-width: $pc + 1) and (min-width: $pc) {
      @content;
    }
  }
  @else if $media= pc_tablet {
    @media only screen and (min-width: $tablet - 1) {
      @content;
    }
  }
}

实施例

body {
  @include responsive(pc) {
    background: red;
  }
  @include responsive(tablet) {
    background: yellow;
  }
  @include responsive(phone) {
    background: green;
  }
}