在这篇文章中,我将首先介绍媒体类型和媒体特征描述符,然后我将解释媒体查询。
在媒体查询和@import声明中,媒体类型允许我们决定在哪个媒体上加载一个CSS文件,或者一个CSS片段。
我们有以下几种媒体类型
all表示所有的媒体print打印时使用的screen当页面呈现在屏幕上时使用的媒体speech用于屏幕阅读器
screen 是默认的。
在过去,我们有更多这样的东西,但大多数被废弃了,因为它们被证明不是确定设备需求的有效方法。
我们可以像这样在@import语句中使用它们。
@import url(myfile.css) screen;
@import url(myfile-print.css) print;
我们可以在多个媒体类型上加载一个CSS文件,用逗号分隔每个媒体类型。
@import url(myfile.css) screen, print;
同样的方法也适用于HTML中的link 标签。
<link rel="stylesheet" type="text/css" href="myfile.css" media="screen" />
<link rel="stylesheet" type="text/css" href="another.css" media="screen, print" />
我们并不局限于只在media 属性和@import 声明中使用媒体类型。还有更多
首先,我们来介绍一下媒体特征描述符。它们是额外的关键字,我们可以将其添加到link 的media 属性或@import 声明中,以表达对加载CSS的更多条件。
下面是它们的列表。
widthheightdevice-widthdevice-heightaspect-ratiodevice-aspect-ratiocolorcolor-indexmonochromeresolutionorientationscangrid
它们中的每一个都有相应的最小*和最大*,例如。
min-width,max-widthmin-device-width,max-device-width
等等。
其中有些接受一个长度值,可以用px 或rem 或任何长度值表示。这就是width,height,device-width,device-height 的情况。
举例来说。
@import url(myfile.css) screen and (max-width: 800px);
注意,我们用括号中的媒体特征描述符来包装每个区块。
有些接受一个固定的值。orientation, 用于检测设备方向,接受portrait 或landscape 。
例子。
<link rel="stylesheet" type="text/css" href="myfile.css" media="screen and (orientation: portrait)" />
scan,用于确定屏幕的类型,接受progressive (用于现代显示器)或interlace (用于老式CRT设备)。
其他一些则需要一个整数。
比如color ,它检查设备使用的每个颜色成分的比特数。非常低级,但你只需要知道它在那里,供你使用(像grid,color-index,monochrome )。
aspect-ratio 和 接受一个代表视口宽度和高度比例的比率值,它以分数表示。device-aspect-ratio
例子。
@import url(myfile.css) screen and (aspect-ratio: 4/3);
resolution 代表设备的像素密度,用分辨率数据类型表示,如 。dpi
例子。
@import url(myfile.css) screen and (min-resolution: 100dpi);
逻辑运算符
我们可以使用and 来组合规则。
<link rel="stylesheet" type="text/css" href="myfile.css" media="screen and (max-width: 800px)" />
我们可以用逗号进行 "或 "类型的逻辑运算,将多个媒体查询结合起来。
@import url(myfile.css) screen, print;
我们可以使用not 来否定一个媒体查询。
@import url(myfile.css) not screen;
重要的是:
not只能用来否定整个媒体查询,所以它必须放在它的开头(或逗号之后)。
所有我们看到的应用于@import或link HTML标签的上述规则,也可以应用于CSS内部。
你需要把它们包在一个@media () {} 结构中。
例子。
@media screen and (max-width: 800px) {
/* enter some CSS */
}
而这是响应式设计的基础。
媒体查询可能相当复杂。这个例子只在屏幕设备、宽度在600到800像素之间、方向是横向的情况下应用CSS。
@media screen and (max-width: 800px) and (min-width: 600px) and (orientation: landscape) {
/* enter some CSS */
}