响应式设计
响应式设计让页面在不同设备(手机、平板、电脑)上都能良好显示。核心手段是媒体查询和弹性布局。
媒体查询
@media (max-width: 768px) { ... } 表示屏幕宽度 ≤768px 时应用括号内样式。常用断点:768px(平板)、480px(手机)。移动端优先写法用 min-width。
响应式四件套
meta viewport:<meta name="viewport" content="width=device-width, initial-scale=1.0">;- 相对单位:%、rem、vw/vh;
- 弹性布局:Flex / Grid 自动换行;
- 媒体查询:针对性调整。
原则:先保证手机端可用(移动优先),再用 min-width 逐级增强桌面体验。
代码示例
<style>
.container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
max-width: 960px;
margin: 0 auto;
padding: 16px;
}
.box {
padding: 20px;
background: #f0f4ff;
border-radius: 8px;
text-align: center;
}
/* 手机端:改为单列 */
@media (max-width: 600px) {
.container { grid-template-columns: 1fr; }
.box { font-size: 14px; }
}
/* 平板端:两列 */
@media (min-width: 601px) and (max-width: 900px) {
.container { grid-template-columns: 1fr 1fr; }
}
</style>
<div class="container">
<div class="box">模块 A</div>
<div class="box">模块 B</div>
</div>
📚 CSS 属性速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
color: #333; | 文字颜色 |
background: #fff; | 背景色 / 背景图 |
font-size: 16px; | 字号 |
font-family: Arial; | 字体 |
font-weight: bold; | 字重(加粗) |
margin: 10px; | 外边距(上右下左) |
padding: 10px; | 内边距 |
border: 1px solid #ccc; | 边框:粗细 样式 颜色 |
border-radius: 8px; | 圆角 |
width: 100%; | 宽度 |
height: 200px; | 高度 |
display: flex; | 弹性布局(现代布局主力) |
display: none; | 隐藏元素 |
position: relative / absolute / fixed; | 定位方式 |
top / left / right / bottom | 定位偏移 |
text-align: center; | 文字水平对齐 |
line-height: 1.6; | 行高 |
overflow: hidden; | 内容溢出处理 |
box-shadow: 0 2px 8px rgba(0,0,0,.1); | 阴影 |
transition: all .3s; | 过渡动画 |
cursor: pointer; | 鼠标手型 |
z-index: 10; | 层叠顺序 |
max-width: 1200px; margin: 0 auto; | 容器居中(经典写法) |
@media (max-width: 768px) {} | 响应式断点 |
:hover | 鼠标悬停状态 |