jiedinghui 2020-01-10
继承了 CSS2 多媒体类型的所有思想: 取代了查找设备的类型,CSS3 根据设置自适应显示。
媒体查询可用于检测很多事情,例如:
目前很多针对苹果手机,Android 手机,平板等设备都会使用到多媒体查询。
多媒体查询由多种媒体组成,可以包含一个或多个表达式,表达式根据条件是否成立返回 true 或 false。
@media not|only mediatype and (expressions) {
CSS 代码...;
}如果指定的多媒体类型匹配设备类型则查询结果返回 true,文档会在匹配的设备上显示指定样式效果。
除非你使用了 not 或 only 操作符,否则所有的样式会适应在所有设备上显示效果。
你也可以在不同的媒体上使用不同的样式文件:
<link rel="stylesheet" media="mediatype and|not|only (expressions)" href="print.css">
使用多媒体查询可以在指定的设备上使用对应的样式替代原有的样式。
规则允许在相同样式表为不同媒体设置不同的样式。
在下面的例子告诉我们浏览器屏幕上显示一个 14 像素的 Verdana 字体样式。但是如果页面打印,将是 10 个像素的 Times 字体。请注意,font-weight 在屏幕上和纸上设置为粗体:
@media screen
{
p.test {font-family:verdana,sans-serif;font-size:14px;}
}
@media print
{
p.test {font-family:times,serif;font-size:10px;}
}
@media screen,print
{
p.test {font-weight:bold;}
}2、以下实例在屏幕可视窗口尺寸大于 480 像素时将菜单浮动到页面左侧:
@media screen and (min-width: 480px) {
#leftsidebar {width: 200px; float: left;}
#main {margin-left:216px;}
}.example {
padding: 20px;
color: white;
}
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {
.example {background: red;}
}
/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {
.example {background: green;}
}
/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {
.example {background: blue;}
}
/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) {
.example {background: orange;}
}
/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {
.example {background: pink;}
}/* 520 到 699px 宽度 - 添加邮箱图标
大于 1151px 宽度 - 添加图标
我们没有编写额外的查询块,我们可以在已有的查询媒体后使用逗号分隔来添加其他媒体查询 (类似 OR 操作符): */
@media screen and (max-width: 699px) and (min-width: 520px), (min-width: 1151px) {
#nav li a {
padding-left: 30px;
background: url(email-icon.png) left center no-repeat;
}
}
/* 700 到 1000px - 添加文本前缀信息 */
@media screen and (max-width: 1000px) and (min-width: 700px) {
#nav li a:before {
content: "Email: ";
font-style: italic;
color: #666666;
}
}
/* 大于 1001px 宽度 - 添加邮件地址 */
@media screen and (min-width: 1001px) {
#nav li a:after {
content: " (" attr(data-email) ")";
font-size: 12px;
font-style: italic;
color: #666666;
}
}