CSS3媒体查询详解(media)
一、demo初体验
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
/* 这句话的意思就是: 在我们屏幕上 并且 最大的宽度是 800像素 设置我们想要的样式 */
/* max-width 小于等于800 */
/* 媒体查询可以根据不同的屏幕尺寸在改变不同的样式 */
/*下面实现的效果是,屏幕可视区域在(500,800]之间是粉红色,小于等于500的时候是紫色*/
@media screen and (max-width: 800px) {
body {
background-color: pink;
}
}
@media screen and (max-width: 500px) {
body {
background-color: purple;
}
}
</style>
</head>
<body>
</body>
</html>
二、注意
min-width和max-width定义的是页面可见区域的最小宽度和最大宽度。
max-width和min-width都是包含等于的,例如:
三、案例演示
媒体查询修改背景颜色
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<style>
/* 1. 媒体查询一般按照从大到小或者 从小到大的顺序来 */
/* 2. 小于540px 页面的背景颜色变为蓝色 */
@media screen and (max-width: 539px) {
body {
background-color: blue;
}
}
/* 3. 540 ~ 970 我们的页面颜色改为 绿色 */
/* @media screen and (min-width: 540px) and (max-width: 969px) {
body {
background-color: green;
}
} */
@media screen and (min-width: 540px) {
body {
background-color: green;
}
}
/* 4. 大于等于970 我们页面的颜色改为 红色 */
@media screen and (min-width: 970px) {
body {
background-color: red;
}
}
/* 5. screen 还有 and 必须带上不能省略的 */
/* 6. 我们的数字后面必须跟单位 970px 这个 px 不能省略的 */
</style>
</head>
<body>
</body>
</html>
但是,里面会有一个坑,如下:
以下面代码为例,单独使用一对min-width和max-width,范围是>=最小值且<=最大值,当时想无缝衔接,就把区间写成[769,1211]和[1212,1230],但是实际演示时发现,前面的1211给我把闭区间变成了开区间/(ㄒoㄒ)/~~
最后作用区域为[769,1211)和[1212,1230]
导致769-1210变红,1212-1230变黄,然后唯独1211这个尺寸没人管了拉缩浏览器宽度到1211时为初始绿色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin:0;padding:0;}
html,body{height:100%;}
#one{height:100%;background-color: green;}
@media screen and (min-width:769px) and (max-width:1211px){
#one{
background:red;
}
}
@media screen and (min-width:1212px) and (max-width:1230px){
#one{
background:yellow;
}
}
</style>
</head>
<body>
<div id="one"></div>
</body>
</html>
如果连续区域衔接时,应该将尺寸包含进去。
正确写法:
@media screen and (min-width:769px) and (max-width:1212px){
#one{
background:red;
}
}
@media screen and (min-width:1212px) and (max-width:1230px){
#one{
background:yellow;
}
}
转载自:https://juejin.cn/post/7213022785367359543