Appearance
CSS 响应式与移动端
响应式设计 · 像素密度 · 1px 问题 · 小字体 · CSS3 新特性
1. 响应式设计
- 通过
@media媒体查询适配不同屏幕 - 需声明 viewport meta 标签
- 使用相对单位(rem/vw/vh/em)
移动端适配两个维度:
- 适配不同像素密度(媒体查询选择不同精度图片)
- 适配不同屏幕大小(按比例还原设计稿)
2. 物理像素 / 逻辑像素 / 像素密度
- CSS 像素(逻辑像素):web 开发使用的抽象单位
- 物理像素:设备屏幕实际像素
- DPR:
devicePixelRatio = 物理像素 / CSS像素 - @2x/@3x 图片:1 逻辑像素 = 2/3 物理像素,图片像素需 ≥ 物理像素
3. 1px 问题
原因:Retina 屏 DPR=2,CSS 的 1px 用 2 个物理像素渲染,看起来粗。
方案一:直接写 0.5px(兼容性差,iOS 8+)
方案二(推荐):伪元素放大后缩小
css
.border-1px:after {
content: '';
position: absolute;
width: 200%; height: 200%;
border: 1px solid #000;
transform: scale(0.5);
transform-origin: top left;
}方案二升级(Less + 媒体查询):
less
.border(@borderWidth: 1px; @borderColor: #ccc) {
position: relative;
&:before {
content: '';
position: absolute;
width: 200%; height: 200%;
border-width: @borderWidth;
border-color: @borderColor;
}
@media (-webkit-min-device-pixel-ratio: 2) {
&:before { transform: scale(0.5); }
}
@media (-webkit-min-device-pixel-ratio: 3) {
&:before { transform: scale(0.33); }
}
}开源库实现:
- Vant:伪元素 +
scale(0.5),四边用top/right/bottom/left: -50% - Ant Design Mobile:
min-resolution: 2dppx媒体查询;大写1PX防止 postcss-pxtorem 转换
4. 小于 12px 字体
Chrome 默认最小字体 12px。
方案:
transform: scale(0.75)(缩放整个元素)- 使用图片替代(内容固定时)
5. CSS3 新特性
- 新选择器:
:not()、:nth-child() border-radius圆角box-shadow/text-shadow阴影linear-gradient/radial-gradient渐变transform(旋转/缩放/倾斜/平移)transition/animation动画flex弹性布局@media媒体查询vw/vh视口单位
6. link 与 @import
| link | @import | |
|---|---|---|
| 类型 | XHTML 标签 | CSS 规则 |
| 加载时机 | 页面加载时同时 | 页面加载完再加载 |
| 兼容性 | 无问题 | CSS2.1,低版本不支持 |
| JS 控制 | 支持 | 不支持 |