媒体查询:支持不同的视口

11 篇文章 0 订阅
10 篇文章 0 订阅

没有CSS3的媒体查询模块,就不能针对设备特性(如视口宽度)设置特定CSS样式。

媒体查询基本语法

将下面这段代码插入到页面后,调整浏览器大小看效果!
body{
background-color:grey;
}
@media screen and (max-width:960px){
	body{
	background-color:red;
	}
}
@media screen and (max-width:768px){
	body{
	background-color:orange;
	}
}
@media screen and (max-width:550px){
	body{
	background-color:yellow;
	}
}
@media screen and (max-width:320px){
	body{
	background-color:green;
	}
}
接下来,让我们继续分析媒体查询,学习如何对其进行充分利用。

1.<link>方式

在css2中,我们知道可以通过<link>标签的media属性为样式表指定设备类型(如显示屏幕或打印机)
如:
<link rel='styleesheet' type='text/css' media ='screen' href='screen-styles.css' >

相对于css3,媒体查询能问的问题要多一点,例如,媒体查询可以问:“你是一块纵向放置的显示屏吗?”
如:
<link rel='styleesheet' type='text/css' media ='screenand (orientation:portrait)' href='portrait-screen-styles.css' >

还可以在媒体查询开头追加not则会天道该查询的逻辑。
如:
<link rel='styleesheet' type='text/css' media ='notscreen and (orientation:portrait)' href='portrait-screen-styles.css' >

也可以将多个表达式组合在一起。如,限制只有视口宽度大于800px的显示屏设备才会加载该文件。
如:
<link rel='styleesheet' type='text/css' media ='screen and (orientation:portrait)and (min-width:800px)' href='800width-portrait-screen-styles.css' >

更进一步,还可以写一个媒体查询列表。查询列表中的任何一个查询为真,则加载文件。
如:
<link rel='styleesheet' type='text/css' media ='screen and (orientation:portrait) and (min-width:800px), projection' href='800width-portrait-screen-styles.css' >

这里有几点需要注意:
    1. 媒体查询之间使用逗号分隔。
    2. 媒体类型与表达式之间以and连接,每个媒体类型可以有多个表达式
    3. 你会注意到在projection之后,没有and,也没有后续的表达式,意味着只要是projection就满足条件。本例中,样式会应用于投影仪。
    4. 媒体类型可以省略,如@media (min-width: 480px) 默认的媒体类型为all。

2.@import方式

如:
@import url("phone.css") screen and (max-width:360px);

也可以创建一个查询范围。
如:
@import url("phone.css") screen and (max-width:360px and (max-width:460px));


3.媒体特性介绍

在语句构造上,媒体特性非常类似于CSS的属性,都由名称和值组成。下面列出媒体特性和CSS属性的不同点:
    1. CSS属性用于声明如何呈现页面的信息;媒体特性则是一个用于判断输出设备是否满足要求的表达式。
    2. 大部分媒体特性支持min和max前缀,表示应用于大于等于或者小于等于某个值的情况。
    3. CSS属性要求必须有值;媒体特性则可以没有值,媒体查询表达式的返回值除了true就是false。
    4. CSS属性可以接受多个复合值作为值;媒体特性只接受单个值。


4.主要媒体特性

width:显示区域的宽度

height:显示区域的高度

device-width:设备屏幕的宽度

device-height:设备屏幕的高度

orientation:横屏或竖屏

aspect-ratio:显示区域的宽高比

device-aspect-ratio:设备屏幕宽高比

resolution:设备屏幕的分辨率

color: number of bits per color component of the output device

color-index:number of entries in the color lookup table of the output device

monochrome:number of bits per pixel in a monochrome frame buffer (0 if the device is not monochrome.)

IE9支持以上媒体特性

参考

W3C CSS3 Media Queries 参考:

http://www.w3.org/TR/css3-mediaqueries/

Media typeMedia query(一篇不错的介绍文章):

http://www.qianduan.net/media-type-and-media-query.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值