响应式设计最佳实践
响应式设计让网站适配各种屏幕尺寸。
Viewport 设置
<meta name="viewport" content="width=device-width, initial-scale=1.0">
媒体查询
/* 移动优先 */
.container {
padding: 10px;
}
/* 平板 */
@media (min-width: 768px) {
.container {
padding: 20px;
}
}
/* 桌面 */
@media (min-width: 1024px) {
.container {
padding: 30px;
max-width: 1200px;
margin: 0 auto;
}
}
断点选择
/* 常用断点 */
$breakpoints: (
xs: 0,
sm: 576px,
md: 768px,
lg: 992px,
xl: 1200px
);
/* Mixin */
@mixin respond-to($breakpoint) {
@media (min-width: map-get($breakpoints, $breakpoint)) {
@content;
}
}
/* 使用 */
.element {
font-size: 14px;
@include respond-to(md) {
font-size: 16px;
}
@include respond-to(lg) {
font-size: 18px;
}
}
弹性布局
/* Flexbox */
.container {
display: flex;
flex-wrap: wrap;
}
.item {
flex: 1 1 300px; /* flex-grow flex-shrink flex-basis */
}
/* Grid */
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
响应式字体
/* 使用 rem 和 em */
html {
font-size: 16px;
}
@media (min-width: 768px) {
html {
font-size: 18px;
}
}
/* 视口单位 */
.hero-title {
font-size: calc(24px + 3vw);
}
/* Clamp 函数 */
.title {
font-size: clamp(16px, 2vw + 1rem, 24px);
}
响应式图片
img {
max-width: 100%;
height: auto;
}
/* 艺术指导 */
<picture>
<source media="(min-width: 1024px)" srcset="large.jpg">
<source media="(min-width: 768px)" srcset="medium.jpg">
<img src="small.jpg" alt="Responsive image">
</picture>
/* 响应式图片集 */
<img
srcset="small.jpg 300w, medium.jpg 600w, large.jpg 1200w"
sizes="(min-width: 768px) 50vw, 100vw"
src="medium.jpg"
alt="Responsive image"
>
隐藏内容
/* 仅在移动端显示 */
.mobile-only {
display: block;
}
@media (min-width: 768px) {
.mobile-only {
display: none;
}
}
/* 仅在桌面显示 */
.desktop-only {
display: none;
}
@media (min-width: 768px) {
.desktop-only {
display: block;
}
}
响应式表格
/* 水平滚动 */
.table-container {
overflow-x: auto;
}
/* 卡片式表格 */
@media (max-width: 767px) {
table, thead, tbody, th, td, tr {
display: block;
}
thead tr {
display: none;
}
tr {
margin-bottom: 10px;
border: 1px solid #ddd;
}
td {
display: flex;
justify-content: space-between;
padding: 10px;
}
td::before {
content: attr(data-label);
font-weight: bold;
}
}
测试工具
/* 显示当前断点 */
body::before {
content: "xs";
position: fixed;
top: 0;
right: 0;
padding: 5px 10px;
background: rgba(0,0,0,0.8);
color: white;
font-size: 12px;
z-index: 9999;
}
@media (min-width: 576px) {
body::before { content: "sm"; }
}
@media (min-width: 768px) {
body::before { content: "md"; }
}
@media (min-width: 992px) {
body::before { content: "lg"; }
}
@media (min-width: 1200px) {
body::before { content: "xl"; }
}
最佳实践
- 移动优先 - 从小屏幕开始设计
- 相对单位 - 使用 rem、em、vw、vh
- 弹性布局 - Flexbox 和 Grid
- 渐进增强 - 基础功能优先
- 测试覆盖 - 在真实设备上测试
CSS
返回首页