媒体查询
媒体查询 用于将 CSS 定向到特定的媒体类型和媒体特性。例如,样式可以应用于打印,或者应用于特定尺寸的屏幕。
应用媒体查询
媒体查询可以添加到 link HTML 元素中
<link rel="stylesheet" href="this.css" media="print">
<!-- applies an external print-only stylesheet -->
<link rel="stylesheet" href="that.css" media="screen and (max-width: 800px)">
<!-- applies an external stylesheet to screens up to 800 pixels wide -->
媒体查询也可以使用 @media 规则嵌入到样式表中
@media print {
body {
font-family: "Times New Roman", Times, serif;
}
/* etc. */
}
/* applies styles to print only */
@media screen and (max-width: 800px) {
body {
padding: 0;
}
/* etc. */
}
/* applies styles to screens up to 800 pixels wide */
也可以使用 @import(例如,@import url(this.css) print)。
媒体类型
screen 和 print 是最常见的媒体类型。all 也可以使用,并且是媒体查询的默认状态。其他支持不稳定的类型包括 braille、embossed、handheld、projection、speech、tty 和 tv。
媒体特性
| 特性 | 描述 | 可能的值 |
|---|---|---|
|
显示区域宽度。 | [长度],例如 800px |
|
显示区域高度。 | [长度],例如 20em |
|
屏幕宽度。 | [长度],例如 2in |
|
屏幕高度。 | [长度],例如 10cm |
orientation |
纵向(当高度大于或等于宽度时)或横向(当宽度大于高度时)。 |
|
|
width 值与 height 值之比。 |
[比例],例如 2/1 |
|
device-width 值与 device-height 值之比。 |
[比例],例如 16/9 |
|
屏幕每个颜色分量的位数。 | [整数]0 表示设备不是彩色的。没有值的 color 等同于 min-color: 1(设备是彩色的)。 |
|
设备颜色查找表的条目数。 | [整数]0 表示设备不使用颜色查找表。没有值的 color-index 等同于 min-color-index: 1(设备使用颜色查找表)。 |
|
灰度设备上每像素的位数。 | [整数]0 表示设备不是灰度的。没有值的 monochrome 等同于 min-monochrome: 1(设备是灰度的)。 |
|
设备的像素密度。 | [分辨率],例如 300dpi |
scan |
与 tv 媒体类型一起使用。设备的扫描方式。 |
|
grid |
设备是网格(如电传打字机式终端)还是位图。 | [整数]0 表示设备不是网格的。没有值的 grid 等同于 grid: 1(设备是网格的)。 |
组合媒体查询
逻辑 OR:逗号分隔列表
逗号分隔的列表将把样式应用于多个媒体查询。
@media screen, projection {
/* CSS applied if device is screen OR projection */
}
逻辑 AND:and
and 关键字将组合媒体查询。
@media print and (min-resolution: 150dpi) {
/* CSS applied if device is print AND resolution is at least 150dpi */
}
逻辑 NOT:not
not 关键字将排除媒体查询。
@media not screen {
/* CSS applied if device is NOT screen */
}
