巧用scss实现一个通用的媒介查询代码

巧用scss实现一个通用的媒介查询代码

效果展示

实现代码

html 复制代码
<template>
  <div class="page-root">
    <div class="header"></div>
    <div class="content">
      <div class="car-item" v-for="item in 9"></div>
    </div>
  </div>
</template>

<script setup>

</script>

<style scoped lang="scss">
// 断点列表
$breakpoints: (
    's':(
            320px,
            767px
    ),
    'm':(
            768px,
            991px
    ),
    'l':(
            992px,
            1200px
    ),
    'xl':1201px,
);

// 混合
@mixin respond-to($name){
  $bp:map-get($breakpoints,$name);
  @if type-of($bp) == "list"{
    $min:nth($bp,1);
    $max:nth($bp,2);

    @media (min-width:$min) and (max-width:$max){
      @content;
    }
  }
  @else{
    @media (min-width:$bp){
      @content;
    }
  }
}

.page-root{
  background-color: #f1f1f1;
  height: 100vh;
  width: 100vw;
  padding: 20px 10%;
  overflow: auto;
  @include respond-to('s'){
    padding: 10px;
  }
  @include respond-to('m'){
    padding: 20px 5%;
  }
  .header{
    height: 60px;
    width: 100%;
    background-color: white;
  }
  .content{
    margin-top: 15px;
    display: grid;
    grid-template-columns: repeat(3,1fr);
    gap: 15px;
    @include respond-to('s'){
      gap: 10px;
      margin-top: 10px;
      grid-template-columns: repeat(1,1fr);
    }
    @include respond-to('m'){
      grid-template-columns: repeat(2,1fr);
    }
    .car-item{
      aspect-ratio: 16/9;
      background-color: white;
    }
  }
}
</style>

代码解析

  • $breakpoints 用作定义一个map,代码中我们定义了不同屏幕的尺寸,如果值是一个数组,也用小括号包裹起来
  • map-get($breakpoints,$name) 从map中获取指定的value,第一个参数时map,第二个参数是key
  • type-of 用于判断一个值的类型,如果是数组类型则返回 list
  • nth($bp,1) 从数组中获取第一项
  • @content 类似与插槽,在 @include 的方法体中编写的样式会被用于这里

基于以上我们就实现了一个通用的媒体查询代码,以后在开发过程中如果需要适配不同的设备,我们只需要使用 @include 为不同大小的设备编写不同的样式即可,不需要每次都去编写重复的媒介查询代码

相关推荐
青皮桔31 分钟前
CSS实现百分比水柱图
前端·css
失落的多巴胺31 分钟前
使用deepseek制作“喝什么奶茶”随机抽签小网页
javascript·css·css3·html5
影子信息36 分钟前
vue 前端动态导入文件 import.meta.glob
前端·javascript·vue.js
青阳流月37 分钟前
1.vue权衡的艺术
前端·vue.js·开源
样子201841 分钟前
Vue3 之dialog弹框简单制作
前端·javascript·vue.js·前端框架·ecmascript
kevin_水滴石穿42 分钟前
Vue 中报错 TypeError: crypto$2.getRandomValues is not a function
前端·javascript·vue.js
666HZ6661 小时前
微信小程序中scss、ts、wxml
微信小程序·小程序·scss
孤水寒月2 小时前
给自己网站增加一个免费的AI助手,纯HTML
前端·人工智能·html
CoderLiu2 小时前
用这个MCP,只给大模型一个figma链接就能直接导出图片,还能自动压缩上传?
前端·llm·mcp
伍哥的传说2 小时前
鸿蒙系统(HarmonyOS)应用开发之实现电子签名效果
开发语言·前端·华为·harmonyos·鸿蒙·鸿蒙系统