媒体查询 @media
约 571 字大约 2 分钟
2025-04-12
Sass 中的 @media
指令用法与原生 CSS 的媒体查询语法完全兼容,但通过 Sass 的特性(如嵌套、变量、混合宏等)可以更高效地组织代码。以下是详细用法和示例:
一、基础用法
Sass 允许在选择器内部嵌套媒体查询,生成的 CSS 会自动将媒体查询提升到外层。
.container {
width: 100%;
// 嵌套媒体查询
@media (min-width: 768px) {
width: 750px;
}
}
编译结果:
.container {
width: 100%;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
二、结合变量使用
使用变量定义断点,提升代码可维护性。
$tablet: 768px;
$desktop: 1024px;
.sidebar {
width: 100%;
@media (min-width: $tablet) {
width: 250px;
}
}
三、结合混入(Mixin)封装
通过混合宏复用媒体查询逻辑,简化代码。
1、基本混入
@mixin respond-to($breakpoint) {
@media (min-width: $breakpoint) {
@content;
}
}
.header {
font-size: 1rem;
@include respond-to(768px) {
font-size: 1.2rem;
}
}
2、支持多设备类型的混入
@mixin media($type, $breakpoint) {
@if $type == "mobile" {
@media (max-width: $breakpoint - 1px) {
@content;
}
} @else if $type == "desktop" {
@media (min-width: $breakpoint) {
@content;
}
}
}
.card {
@include media("mobile", 768px) {
padding: 10px;
}
}
四、结合函数(Function)和 映射 Map
使用函数动态返回媒体查询条件。
$breakpoints: (
"phone": 320px,
"tablet": 768px,
"desktop": 1024px,
);
@function get-breakpoint($name) {
@return map-get($breakpoints, $name);
}
@mixin for-device($device) {
@media (min-width: get-breakpoint($device)) {
@content;
}
}
.grid {
@include for-device("tablet") {
grid-template-columns: repeat(2, 1fr);
}
}
五、组合多个媒体条件
通过 and
、,
组合多个查询条件。
.component {
// 同时满足屏幕和最小宽度
@media screen and (min-width: 768px) {
color: red;
}
// 满足横屏或最小高度
@media (orientation: landscape), (min-height: 500px) {
padding: 20px;
}
}
六、多层嵌套
Sass 支持深层嵌套媒体查询,但需注意生成后的代码结构。
.parent {
@media (min-width: 768px) {
color: blue;
.child {
@media (orientation: landscape) {
color: green;
}
}
}
}
编译结果:
@media (min-width: 768px) {
.parent {
color: blue;
}
}
@media (min-width: 768px) and (orientation: landscape) {
.parent .child {
color: green;
}
}
七、注意事项
插值语法:旧版 Sass 中变量需用
#{}
包裹:@media (min-width: #{$breakpoint}) { ... }
逻辑运算符:复杂逻辑建议拆分,避免错误。
移动优先:推荐优先编写移动端样式,再通过
min-width
逐步增强。
通过结合 Sass 的特性,可以大幅简化响应式设计的代码管理。重点是利用变量、混合宏和嵌套来提升可维护性。
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于