响应式Web设计:HTML5和CSS3实战(第2版)
第二章 媒体查询
- 除了IE8及以下,主流浏览器都支持媒体查询
2.1 为什么响应式需要媒体查询
- 届时,css并不支持真正的条件逻辑和可编程特性
推荐书目
- 《Sass和Compass设计师指南》
2.2 媒体查询的语法
- 在css中使用:
img {
@media screen and (max-width: 50em);
}
- 在link中使用:
<link rel="stylesheet" type="text/css" media="screen and (orientation: portrait)" href="example.css">
2.3 组合媒体查询
- 串在一起
<link rel="stylesheet" type="text/css" media="screen and (orientation: portrait) and (max-width: 320px), projection" href="example.css">
- 逗号分隔每个媒体查询表达式
2.3.1 省略screen
- 不指定关键字,则默认是all,包括screen
2.3.2 媒体查询可以侦测的特性
- 较常用:
特性 | 解释 |
---|---|
width | 视口宽度 |
height | 视口高度 |
device-width | 渲染表面的宽度(即屏幕宽度) |
device-height | 渲染表面的高度(即屏幕高度) |
orientation | 设备方向是垂直还是水平 |
aspect-ratio | 视口宽高比 |
grid | 设备基于栅格还是位图 |
resolution | 屏幕或打印分辨率 |
2.4 通过媒体查询修改设计
2.4.1 任何css都可以放在媒查内
2.4.2 针对高分辨率设备的媒查
@media (min-resolution: 2dppx) { ... }
2.5 注意事项
2.5.1 使用媒查链接不同css文件
@import url("iphone.css") screen and (max-width: 680px);
- css属于阻塞型内容,浏览器需要下载和解析,然后再渲染页面
- 不符合媒查的css文件被“延缓执行”,到页面加载后再处理(并非不下载)
- 所有文件都被下载后,如果有的文件不必立即使用,浏览器就不会让它影响页面渲染
- 如,下载了6个css文件,在渲染爷面前,只解析针对当前视口大小的样式表
2.5.2 初步页面性能优化
- 性能优化漫谈:
- 所有图片都经过了压缩
- 所有脚本都拼接并缩短了
- 所有资源都采用了gzip压缩
- 所有静态资源都缓存到了CDN
- 所有多余的css规则都被清除了
2.5.3 媒查适合写在css表中
2.6 组合媒查 vs 分块摆放
- 分散放(推荐)
.thing {
width: 50%;
}
@media (min-width: 30rem) {
.thing {
width: 75%;
}
}
.thing2 {
width: 50%;
}
@media (min-width: 30rem) {
.thing2 {
width: 75%;
}
}
- 组合放
.thing {
width: 50%;
}
.thing2 {
width: 50%;
}
@media (min-width: 30rem) {
.thing {
width: 75%;
}
.thing2 {
width: 75%;
}
}
2.7 viewpoet的meta标签
推荐使用
<meta name="viewport" content="width=device-width, initial-scale:1.0">
网友评论