使用 SCSS 统一媒体查询

写在前面

文末有我帮助500多人拿到前端offer的文章 !!!

一般在项目为了适配多种设备,常用的一种方式就是使用媒体查询,比如我们需要给一个卡片在手机、pad、笔记本与电脑中显示不同的宽度,那么代码一般会这样写:

  .card {
    height: 300px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
  }
  /* 手机 */
  @media (min-width: 320px) and (max-width: 480px) {
    .card {
      width: 100%;
    }
  }
  /* 平板 */
  @media (min-width: 481px) and (max-width: 768px) {
    .card {
      width: 50%;
    }
  }
  /* 笔记本 */
  @media (min-width: 769px) and (max-width: 1366px) {
    .card {
      width: 33%;
    }
  }
  /* 电脑 */
  @media (min-width: 1367px) {
    .card {
      width: 400px;
    }
  }
  
  .header {
      height: 50px;
  }
  @media (min-width: 320px) and (max-width: 480px) {
      .header {}
  }
  /* ... */

如果css代码比较少的情况下这种写法没什么问题,但是一旦样式类比较多的情况下维护起来就很繁琐,每个样式类都需要写对应的@mediamin-widthmax-width

这种情况下我们可以借助scss来统一维护媒体查询的变量与对应设备的宽度。

/* 这里声明有哪些设备以及对应的宽度 */
$screens: (
  'phone': (320px, 480px),
  'pad': (481px, 768px),
  'laptop': (769px, 1366px),
  'desktop': (1367px)
)

/* 抽出媒体查询逻辑,传入设备名称,并通过 content 接收具体内容 */
@mixin responseScreen($device) {
  /* 通过 map-get 获取对应的设备宽度信息 */
  $width: map-get($screens, $device);
  @if type-of($width) == 'list' {
    @media (min-width: nth($width, 1)) and (max-width: nth($width, 2)) {
      @content;
    }
  } @else {
    @media (min-width: $width) {
      @content;
    }
  }
}

.card {
  height: 300px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 4px;

  /* 使用 */
  @include responseScreen('phone') {
    width: 100%;
  }
  @include responseScreen('pad') {
    width: 50%;
  }
  @include responseScreen('laptop') {
    width: 33%;
  }
  @include responseScreen('desktop') {
    width: 400px;
  }
}

.header {
  height: 50px;

  /* 使用 */
  @include responseScreen('phone') {}
  @include responseScreen('pad') {}
  @include responseScreen('laptop') {}
  @include responseScreen('desktop') {}
}

这样我们就将$screens设备的类型与宽度抽出用map存放可以单独维护,也将媒体查询处理抽出放到mixin混入中,这样如果有修改宽度和媒体查询时,需要更改的代码就会变少。

偏爱前端的晓羽:称作2024很强的前端面试场景题,成功帮助532人拿到offer

给你们推荐一篇我帮助500+名同学完成改造的文章,希望大家看完以后都可以领取到心仪的offer哦

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值