媒体查询
示例代码:
@media screen and (max-width: 960px) {
div {
width: 800px;
height: 500px;
border: 20px solid blue;
background: #ccc;
}
}
解释:
当屏幕发生变化,根据设置的最大值宽度或者最小值宽度时,读取大括号内的代码
@media screen and (当屏幕发生变化,最大宽度到达某一个值得时候,比如max-width:960px时,执行以下代码) {
}
媒体查询一定要放在初始设置的css样式底下,否则会被后面设置的css样式覆盖掉媒体查询所设置的样式,那么媒体查询就不会生效了。
- eg.
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>媒体查询的例子</title>
<style media="screen">
div {
width: 1200px;
overflow: hidden;
margin: 0 auto;
border: 1px solid red;
}
span {
float: left;
width: 25%;
height: 300px;
/*margin-right: 2%;*/
background: url("../chapter10/1.jpg") no-repeat;
background-size: 100% 100%;
}
@media screen and (max-width:600px) {
div {
width: 500px;
}
span {
width: 50%;
/*margin-right: 1%;*/
}
}
</style>
</head>
<body>
<div>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</body>
</html>