移动端优先设计理念
移动端优先(Mobile First)是一种渐进增强的开发策略:先为移动设备编写基础样式,再通过min-width媒体查询逐步为更大屏幕添加布局增强。
/* 基础样式 — 移动端 */
.grid {
display: grid;
grid-template-columns: 1fr;
gap: 16px;
}
/* 平板及以上 */
@media (min-width: 768px) {
.grid { grid-template-columns: repeat(2, 1fr); }
}
/* 桌面端 */
@media (min-width: 1024px) {
.grid { grid-template-columns: repeat(3, 1fr); gap: 24px; }
}
Flexbox 弹性布局
导航栏布局
.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
}
.nav__links {
display: flex;
gap: 1.5rem;
list-style: none;
}
@media (max-width: 768px) {
.nav { flex-direction: column; }
.nav__links { flex-direction: column; }
}
垂直居中与等高列
.card-row {
display: flex;
gap: 24px;
}
.card {
flex: 1;
display: flex;
flex-direction: column;
}
.card__content {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
CSS Grid 二维布局
经典页面布局
.page {
display: grid;
min-height: 100vh;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 280px 1fr;
grid-template-rows: auto 1fr auto;
}
@media (max-width: 768px) {
.page {
grid-template-areas:
"header" "main" "sidebar" "footer";
grid-template-columns: 1fr;
}
}
响应式卡片网格
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 24px;
}
auto-fill + minmax是最强大的响应式布局方案,无需媒体查询即可自动调整列数。
CSS 自定义属性与主题
:root {
--color-primary: #3498db;
--color-text: #2c3e50;
--color-bg: #ffffff;
--spacing-md: 16px;
--spacing-lg: 24px;
--border-radius: 8px;
--shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
[data-theme="dark"] {
--color-primary: #5dade2;
--color-text: #ecf0f1;
--color-bg: #2c3e50;
}
响应式排版
h1 { font-size: clamp(1.75rem, 4vw, 3rem); }
h2 { font-size: clamp(1.5rem, 3vw, 2.25rem); }
p { font-size: clamp(0.875rem, 1.5vw, 1.125rem); }
section { padding: clamp(2rem, 5vw, 4rem) 0; }
clamp()函数实现流体排版,在最小值和最大值之间平滑缩放。
总结
现代CSS布局技术(Flexbox + Grid + 自定义属性)已经非常成熟。结合Mobile First理念和clamp()等现代CSS函数,可以用最少的代码实现优雅的响应式网站。