CSS媒体查询
让我们根据设备显示器的特性为其设定CSS样式。
为什么响应设计需要媒体查询
没有CSS媒体查询模块,就无法针对设备特性(视口宽度)设置特定CSS样式。
媒体查询
由媒体类型和一个或多个检测媒体特性的条件表达式组成,试用媒体查询,可在不改变页面内容的前提下,为特定输出设备定制显示效果。
媒体查询语法
可通过<link>标签的media属性为样式表指定设备类型,媒体查询则能使我们根据设备的各种功能特性来设定相应的样式。
可将媒体查询想象成对浏览器提问,如浏览器回答:YES, 则应用样式,NO,则不应用样式。
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<!-- 写在link标签中的媒体查询(实现依据设备动态加载样式) -->
<!-- 注:projection代表兼容所有投影仪 -->
<link rel="stylesheet" media="screen and (min-width:800px), projection"
href ="min800wide-portrait-screen.css" />
<link rel="stylesheet" media="een and (max-width:700px), projection"
href ="max700wide-portrait-screen.css" />
</head>
<body>
HelloWorld!
</body>
</html>
/* min800wide-portrait-screen.css */
body{
background-color:gray;
color:blue;
}
/* 写在CSS文件中的媒体查询 */
@media screen and (min-width:800px){
body{
background-color:red;
}
}
/* max700wide-portrait-screen.css */
body{
background-color:yellow;
color:red;
}
@media screen and (max-width:700px){
body{
background-color:green;
}
}
媒体查询流检测特性
width:视口宽度
height:视口高度
device-width:设备屏幕宽度
device-height:设备屏幕高度
orientation:检测设备处于横向还是纵向
aspect-ratio:基于视口宽高比,一个16:9显示的屏可这样定义,aspect-ratio:16/9
device-aspect-ratio:基于设备屏幕宽高比
color:颜色位数,min-color:16,会检测设备是否拥有16位颜色
color-index:设备颜色索引表中的颜色数,必须为非负整数
monochrome:检测单色帧缓冲区中每像素使用位数,必须非负整数
resolution:检测屏幕或打印机分辨率
scan:电视机的扫描方式,值可为,progresssive(逐行扫描),interlace(隔行扫描)
grid:检测输出设备是网络设备还是位图设备
注:上述特性,除scan和grid外,可用min和max创建查询范围。
加载媒体查询的最佳方式
建议在已有的样式表中追加媒体查询样式。
阻止移动浏览器自动调整页面大小
IOS, Android浏览器都基于WebKit核心,这2种浏览器以及很多浏览器都支持用viewport meta元素覆盖默认画布缩放设置。
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<!-- 阻止移动浏览器自动调整页面大小 -->
<!-- meta标签中可设置具体宽度(如像素值)或缩放比例,如2.0(设备实际尺寸的2被) -->
<meta name="viewport" content="initial-scale=2.0,width=device-width" />
<title></title>
</head>
<body>
</body>
</html>
媒体查询只是必要条件之一,我们需要流动布局!