CSS媒体查询允许我们基于浏览网站的设备的特性来应用不同的样式申明, 比如通过视口的宽度。对设备提出询问(称作表达式)开始,如果表达式结果为真,媒体查询中的CSS被应用,如果表达式结果为假,媒体查询内的CSS将被忽略。
以@media开头来表示这是一条媒体查询语句。紧跟在@media后面的是一个或者多个表达式,可以判别为真或假。
在创建媒体查询时,必须以媒体类型(此处为screen)作为第一个表达式,相对应的有:print(打印机)、braille(盲文)或者all(全部)等其他类型
示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>媒体查询</title>
<style>
/*媒体查询*/
@media screen and (max-width: 600px) {
body {
background-color: red;
}
#box {
font-size: 20px;
color: #fff;
}
}
@media screen and (min-width: 600px) and (max-width: 800px) {
body {
background-color: green;
}
#box {
font-size: 30px;
color: yellow;
}
}
@media screen and (min-width: 800px) and (max-width: 1000px) {
body {
background-color: blue;
}
#box {
font-size: 40px;
color: #fff;
}
}
@media screen and (min-width: 1000px) {
body {
background-color: purple;
}
#box {
font-size: 50px;
color: pink;
}
}
</style>
</head>
<body>
<div id="box">
<h4> 根据屏幕的尺寸改变背景颜色:</h4>
<p>宽度 < 600 红色</p> <p>宽度 600 - 800 绿色 </p>
<p>宽度 800 - 1000 蓝色 </p>
<p>宽度>1000 紫色</p>
</div>
</body>
</html>