媒体查询知识点整理
1.什么是媒体查询?
媒体查询就是样式表的if语句,通过各种条件去判断到底执行哪一段CSS。
@media only screen and max-width:600px{
.aside{
width:500px;
}
}
兼容性:
<!–[if lt IE 9]>
<script src="http://cdn.staticfile.org/livingston-css3-mediaqueries-js/1.0.0/css3-mediaqueries.js"></script>
<![endif]–>
而HTML5标签,IE9以前也不支持
<!–[if lt IE 9]>
<script src="http://apps.bdimg.com/libs/html5shiv/3.7/html5shiv.min.js"></script>
<![endif]–>
1)媒体类型种类
all:全部媒体类型,这也是默认值,所有设备;*
@media all max-width:600px{
...
}
- screen:通常指PC、手机、pad
- tv:电视
- print:打印机(通常是黑白的)
- projection:投影仪
- handheld:手持设备
- speech:语音设备
- barille:触摸设备
在最新的media query4版中,仅保留了4个类型:all print speech screen,其它设备将不再响应。
2)媒体特征表达式:目前可供验证的特征条件有
- width
- max-width
- min-width
- color : 判断是否是彩色设备
- device-width
- orientation:横(landscape) | 纵 (portrait)
- aspect-ratio:显示宽高
- resolution:分辨率
- min-device-pixel-ratio:物理像素比
@media only screen and (-webkit-min-device-pixel-ratio: 2){
.....
}
2.媒体查询格式
@media 条件1 [逻辑符] 条件2 ....{
...
}
💡Notice:
- 媒体特征(条件)用括号声明—(min-width:500px)
- 特征属性与特性值,用:分隔
- 属性声明完毕后,不要用;结束
@meida screen and (max-width:1000px) and (min-width:800px){
}
3.媒体查询逻辑
(1)与关系(and)
将多个媒体类型与特征联系起来,只有条件全为真是,查询才成立
@media (min-width:320px) and (orientation:landspace){
.aside{
display:none;
}
}
💡Notice:
min 大于等于
max 小于等于
(2)或关系(,)
有一个条件满足,样式就生效
@media (min-width:320px) , (orientation:landspace){
.aside{
display:none;
}
}
(3)非(not)
取反操作(意为’除了’)
not (max-width:600px)
not (all and (max-width:600px))
not (screen and (max-width:600px))
💡Notice:
- not与and合用时,它是对整个查询语句取反,而不是就近
- all无法取反
@media not (all and (min-width:320px) ), (orientation:landspace){
...
}
💡Notice:
- 此时,not只在它所在的查询生效
例:
8bit
32bit
@media (max-width:960px)
@media not handheld and (min-width:360px),screen and (min-width:480px)
@media color {...}
@media all and (min-width: 700px) and (orientation: landscape) { ... }
@media (min-width: 700px), handheld and (orientation: landscape) { ... }
@media not(all and (max-width:480px))
4.媒体查询策略 ******
1)顺序策略
相同代码段,如果书写顺序不同,执行结果也不同
2)min-width与max-width
mobile-first(移动优先)特点:
先开发手机端
所有条件,都用min-width
所有断点为从小到大
考虑样式追加问题(+)
适用于项目从0开始制作.
因为它符合从易到难的特征,是对HTML元素默认特性发挥最好的方式,是CSS叠加现象
desktop-first(桌面优先)特点:
先开发PC页面
所有条件,都用max-width
所有断点为从大到小出现
考虑样式的覆盖问题(—),以及新样式代码的优先级
对原有PC项目进行移动端适配时
这种方式会造成大量的CSS样式覆盖现象
3)断点选择时机
- BOOTSTRAP框架有默认断点
- 手工设置:视口从小到大的变化过程中,当页面变的比较糟糕时,那此时就是断点设置点
6.媒体查询使用
1)链接媒体查询
基于设备
<link rel="stylesheet" href="one.css" media="srceen">
<link rel="stylesheet" href="two.css" media="print">
基于条件
<link rel="stylesheet" href="one.css" media="screen and (min-width:414px)">
💡Notice:
- 对应的样式表文件中,不要再包含查询条件
不推荐,增加多余的请求次数,降低执行效率
2)嵌入媒体查询(推荐方式)
将媒体查询代码,写到原有CSS文件中