前端用Scss简化媒体查询

发布于:2024-04-09 ⋅ 阅读:(71) ⋅ 点赞:(0)

1、演示

2、未优化前的代码

.header {
  width: 100px;
  height: 100px;
  background-color: red;
}
@media (min-width: 320px) and (max-width: 480px) {
  .header {
    width: 10px;
  }
}
@media (min-width: 320px) and (max-width: 480px) {
  .header {
    height: 20px;
  }
}
@media (min-width: 481px) and (max-width: 768px) {
  .header {
    height: 40px;
  }
}
@media (min-width: 769px) and (max-width: 1024px) {
  .header {
    height: 60px;
  }
}
@media (min-width: 1025px) and (max-width: 1200px) {
  .header {
    height: 80px;
  }
}
@media (min-width: 1201px) {
  .header {
    height: 100px;
  }
}

可以想象一下,在真实的项目里面有这么多选择器要写,有这么多根据不同的设备处理不同的样式,这个代码根本看不了。

3、优化方法

 想办法优化成容易书写,容易维护,可以借助预编译器 Sass 或者 less

4、Sass中的混合 

什么叫做混合: 可以提取一部分的公共代码

未编译前的代码,可以公共使用

@mixin flex{
    display: flex;
    justify-content: center;
    align-items: center;
}

.header{
  width: 100%;
  @include flex;
}
.nav{
  @include flex;
}

编译后的代码,会被编译为存粹的Css,最终的运行结果也是这个存粹的Css

.header{
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.nav{
  display: flex;
  justify-content: center;
  align-items: center;
}

5、传递参数

 编译前的scss文件

@mixin flex($layout){
    display: flex;
    justify-content: $layout;
    align-items: $layout;
}

.header{
  width: 100%;
  @include flex(center)
}
.nav{
  @include flex(start)
}

编译后的css文件

.header{
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.nav{
  display: flex;
  justify-content: start;
  align-items: start;
}

6、传递内容

 编译前的scss文件

@mixin flex($layout){
    display: flex;
    justify-content: $layout;
    align-items: $layout;
    @content;
}

.header{
  width: 100%;
  @include flex(center){
    background-color: red;
  }
}
.nav{
  @include flex(start){
    position: relative;
  }
}

 编译前的css文件

.header{
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: red;
}
.nav{
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

7、优化后的代码


$typePoint:(
  'phone':(320px,480px),
  'pad':(481px,768px),  
  'notebook':(769px,1024px),
  'desktop':(1025px,1200px),
  'tv':1201px,
);

@mixin responseTo($type){
    $bp:map-get($typePoint,$type);
    @if type-of($bp) == 'list' {
        @media (min-width: nth($bp,1)) and (max-width: nth($bp,2)) {
            @content;
        }
    } @else {
        @media (min-width: $bp)  {
            @content;
        }
    }
}

.header{
    width: 100%;
    @include responseTo('phone'){
        height: 50px;
    }
    @include responseTo('pad'){
        height: 70px;
    }
    @include responseTo('notebook'){
        height: 90px;
    }
    @include responseTo('desktop'){
        height: 110px;
    }
    @include responseTo('tv'){
        height: 130px;
    }

}

写完保存过后,生成的css文件内容和第二步一模一样,而且上面这个代码只需要做一次,不需要每次都写,项目里面做一次甚至可以跨越项目,后边要做的无非就是使用这个混合