CSS中的媒体查询 – MasterH杂货铺

CSS中的媒体查询

用法

  • link元素的media属性
  • style元素的media属性
  • @import声明的媒体描述符部分
  • @media声明的媒体描述符部分
    媒体查询可以是简单的媒体类型,也可以是复杂的媒体类型和特性的组合

简单的媒体查询

投影环境使用一些不同的样式

h1 { color: maroon; }
@media projection {
    body { background: yellow; }
}

所有媒体中,h1元素的颜色都是红褐色,但在投影媒体中body元素会有一个黄色背景
可以把所有规则都放在一个@media块里

@media all {
    h1 { color: maroon; }
    body { background: yellow; }
}

媒体类型

  • all:用于所有展示媒体
  • print:为有视力的用户打印文档时使用,也在预览打印效果时使用
  • screen:在屏幕媒体(如桌面电脑的显示器)上展示文档时使用。
    下面四种方式都能把一个样式表(或一个规则块)同时应用到屏幕媒体和印刷媒体上

    <link type="text/css" href="frobozz.css" media="screen, print">
    <style type="text/css" media="screen, print">...</style>
    @import url(frobozz.css) screen, print;
    @media screen, print { ... }

媒体描述符

两种方式把指定的外部样式表应用到彩打上,以彩打为例

<link href="print-color.css" type="text/css" media="print and (color)" rel="stylesheet">
@import url(print-color.css) print and (color);

可以通过一个逗号分隔的列表列出多个查询

<link href="print-color.css" type="text/css" media="print and (color), screen and (color-depth: 8)" rel="stylesheet">
@import url(print-color.css) print and (color), screen and (color-depth: 8);

下面两个是等价的

@media all and (min-resolution: 96dpi) { ... }
@media (min-resolution: 96dpi) { ... }

多个特性描述符使用逻辑关键字and连接

and

连接的两个或多个媒体特性必须同时满足条件,整个查询得到的结果才是真值。例如(color) and (orientation: landscape) and (min-device-width: 800px)表示三个条件都要满足:当媒体环境是彩色的、横向放着,而且设备的屏幕宽至少为800像素,才会应用样式表

not

对整个查询取反。假如所以条件都为真,那样式表不会应用到文档上。例如not (color) and (orientation: landscape) and (min-device-width: 800px)表示三个条目都满足时,整个语句得到的结果与之相反。因此当媒体环境是彩色的、横向放着,而且设备的屏幕宽至少为800像素,样式表不会应用到文档上。除此之外的情况下,都将应用样式表。

Related Posts

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注