话不多说直接先上scss代码,就是一个scss的mixin混入代码
@use "sass:meta";
@use "sass:list";
@use "sass:map";
$breakpoints: (
"phone": (
320px,
480px,
),
"pad": (
481px,
768px,
),
"notebook": (
769px,
1024px,
),
"desktop": (
10245px,
1200px,
),
"tv": 1201px,
);
@mixin responseTo($breakname) {
$bp: map.get($breakpoints, $breakname);
@if meta.type-of($bp) == "list" {
@media (min-width: list.nth($bp,1)) and (max-width: list.nth($bp,2)) {
@content;
}
} @else {
@media (min-width: $bp) {
@content;
}
}
}
使用也简单
@include responseTo("notebook") {
div {
background: yellow;
}
}
会编译为
@media (min-width:769px) and (max-width: 1024px) {
div {
background: yellow;
}
}
实际用一下,先创建一个vite项目,这里用vue3的模板,下载sass
yarn add scss -D
下载完后看了一下package.josn里sass版本是1.88.0
vite中要使用公共的scss混入代码的话最好到vite.config.js中加一行简单的配置
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
export default defineConfig({
resolve: {
alias: {
"@": "/src",
},
},
css: {
preprocessorOptions: {
scss: {
javascriptEnabled: true,
additionalData: `@import "@/publicStyle.scss";`,//你创建的scss公共样式代码路径
api: "modern-compiler", //解决scss报的警告
},
},
},
plugins: [vue()],
});
简单创建一个vue文件,再随便创建点元素布局一下
<template>
<div class="content">
<div class="outer_box">
<div class="inner_box">
<div class="fixed_box">
<div
v-for="(item, index) in listArr"
:key="index"
class="box_item"
></div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
const listArr = ref(Array.from({ length: 8 }));
</script>
<style lang="scss" scoped>
.outer_box {
width: 80%;
background: #f06b8e;
border-radius: 10px;
.inner_box {
padding-top: 70%;
position: relative;
}
.fixed_box {
position: absolute;
padding: 20px;
left: 0;
top: 0;
height: 100%;
width: 100%;
display: flex;
justify-content: space-between;
}
.box_item {
width: 8%;
height: 80px;
border-radius: 8px;
background: #ff9800;
}
</style>
效果是这样,一个盒子里有8个小方块

现在假如我要加简单媒介查询修改内部小块的宽度的一个简单响应式
在屏幕1024px-1200px时修改内部小块宽度为30%
在屏幕769px-1024px时宽度为40%并加margin-bottom为20px
在屏幕481-768时宽度为70%,并将外部盒子的justify-content修改为center
@include responseTo("desktop") {
.box_item {
width: 30%;
}
}
@include responseTo("notebook") {
.box_item {
width: 40%;
margin-bottom: 10px;
}
}
@include responseTo("pad") {
.fixed_box {
justify-content: center;
}
.box_item {
width: 70%;
margin-bottom: 20px;
}
}
效果

总结:用了这个配置后,以后再也不用写一大堆@media媒介查询啦,想要其他尺寸的话配置代码里的options就行拉,结构也是个map结构,完结散花!!!