媒体查询与断点
约 344 字大约 1 分钟
布欧-Lewyon
2026-05-16
基本语法
/* 视口宽度 ≥ 768px */
@media (min-width: 768px) {
.container { width: 750px; }
}
/* 视口宽度 ≤ 480px */
@media (max-width: 480px) {
.sidebar { display: none; }
}
/* 范围 */
@media (min-width: 768px) and (max-width: 1024px) {
/* 平板 */
}常用断点
/* Mobile First:从小到大定义 */
/* 默认:手机 (< 576px) */
/* ≥ 576px */
@media (min-width: 576px) { }
/* ≥ 768px 平板 */
@media (min-width: 768px) { }
/* ≥ 992px 桌面 */
@media (min-width: 992px) { }
/* ≥ 1200px 大屏 */
@media (min-width: 1200px) { }
/* ≥ 1400px 超大屏 */
@media (min-width: 1400px) { }Mobile First
先写基础样式(手机),再逐层增强:
/* 基础:手机(单列) */
.grid { display: block; }
/* 平板 */
@media (min-width: 768px) {
.grid { display: grid; grid-template-columns: repeat(2, 1fr); }
}
/* 桌面 */
@media (min-width: 1200px) {
.grid { grid-template-columns: repeat(4, 1fr); }
}暗色模式
:root {
--bg: white;
--text: #333;
}
/* 自动暗色模式 */
@media (prefers-color-scheme: dark) {
:root {
--bg: #1f1f1f;
--text: #e0e0e0;
}
}
body {
background: var(--bg);
color: var(--text);
}减少动画偏好
@media (prefers-reduced-motion: no-preference) {
.animated {
animation: fadeIn 0.5s ease;
}
}
/* prefers-reduced-motion: reduce → 不播放动画 */小结
| 媒体特性 | 用途 |
|---|---|
min-width / max-width | 视口宽度断点 |
prefers-color-scheme | 暗色/亮色模式 |
prefers-reduced-motion | 减少动画 |
pointer: coarse | 触屏设备 |
hover: hover | 可悬停设备 |
