巧用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 为不同大小的设备编写不同的样式即可,不需要每次都去编写重复的媒介查询代码

相关推荐
passerby60611 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅2 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊3 小时前
jwt介绍
前端
爱敲代码的小鱼3 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
Cobyte3 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc