CSS2 中引入的 @media
规则使得为不同的媒体类型定义不同的样式规则成为可能。
示例:您可以为计算机屏幕制定一套样式规则,一套用于 打印机,一种用于手持设备,一种用于电视类型设备,等等。
不幸的是,这些媒体类型从未得到设备、其他设备的大量支持 比打印介质类型。
CSS3 中的媒体查询扩展了 CSS2 媒体类型的想法:不是寻找设备类型, 他们着眼于 设备。
媒体查询可用于检查很多事情,例如:
视口的宽度和高度
设备的宽度和高度
方向(平板电脑/手机处于横向还是纵向模式?)
解决
使用媒体查询是提供定制风格的流行技术 桌面、笔记本电脑、平板电脑和手机(例如 iPhone 和 Android 手机)。
表中的数字指定完全支持 @media
规则的第一个浏览器版本。
Property | |||||
---|---|---|---|---|---|
@media | 21.0 | 9.0 | 3.5 | 4.0 | 9.0 |
媒体查询由媒体类型组成,可以包含一个或多个 表达式,解析为 true 或 false。
@media not|only mediatype and (expressions) {
CSS-Code;
}
查询的结果是 true 如果指定的媒体类型与文档所在的设备类型匹配 正在显示并且媒体查询中的所有表达式均为 true。当媒体查询为真时,相应的样式表或样式规则为 应用,遵循正常的级联规则。
除非您使用 not 或 only 运算符,否则媒体类型是可选的,并且 所有
类型都将被隐含。
您还可以为不同的媒体使用不同的样式表:
<link rel="stylesheet" media="mediatype and|not|only (expressions)" href="print.css">
用于所有媒体类型设备
用于打印机
用于电脑屏幕、平板电脑、智能手机等。
用于大声“朗读”页面的屏幕阅读器
使用媒体查询的一种方法是在样式表内有一个备用 CSS 部分。
以下示例将背景颜色更改为浅绿色,如果 视口宽度为 480 像素或更宽(如果视口小于 480 像素,背景颜色为粉红色):
@media screen and (min-width: 480px) {
body {
background-color: lightgreen;
}
}
自己尝试一下→
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: pink;
}
@media screen and (min-width: 480px) {
body {
background-color: lightgreen;
}
}
</style>
</head>
<body>
<h1>Resize the browser window to see the effect!</h1>
<p>The media query will only apply if the media type is screen and the viewport is 480px wide or wider.</p>
</body>
</html>
以下示例显示了一个菜单,如果满足以下条件,该菜单将浮动到页面左侧: 视口宽度为 480 像素或更宽(如果视口小于 480 像素,菜单将位于内容之上):
@media screen and (min-width: 480px) {
#leftsidebar
{width: 200px; float: left;}
#main
{margin-left: 216px;}
}
自己尝试一下 →
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.wrapper {overflow: auto;}
#main {margin-left: 4px;}
#leftsidebar {
float: none;
width: auto;
}
#menulist {
margin: 0;
padding: 0;
}
.menuitem {
background: #CDF0F6;
border: 1px solid #d4d4d4;
border-radius: 4px;
list-style-type: none;
margin: 4px;
padding: 2px;
}
@media screen and (min-width: 480px) {
#leftsidebar {width: 200px; float: left;}
#main {margin-left: 216px;}
}
</style>
</head>
<body>
<div class="wrapper">
<div id="leftsidebar">
<ul id="menulist">
<li class="menuitem">Menu-item 1</li>
<li class="menuitem">Menu-item 2</li>
<li class="menuitem">Menu-item 3</li>
<li class="menuitem">Menu-item 4</li>
<li class="menuitem">Menu-item 5</li>
</ul>
</div>
<div id="main">
<h1>Resize the browser window to see the effect!</h1>
<p>This example shows a menu that will float to the left of the page if the viewport is 480 pixels wide or wider. If the viewport is less than 480 pixels, the menu will be on top of the content.</p>
</div>
</div>
</body>
</html>
有关媒体查询的更多示例,请转到下一页:CSS MQ 示例。
有关所有媒体类型和功能/表达的完整概述,请查看 我们的 CSS 参考中的 @media 规则。