媒体查询–基础
- 什么是媒体查询 media query
@media screen and (min-width: 900px) {
body {
background-color: red;
}
}
-
为什么需要媒体查询
一套样式不可能适应各种大小的屏幕
针对不同的屏幕大小写样式
让我们的页面在不同大小的屏幕上都能正常显示 -
媒体类型
all(default)
screen / print / speech
@media (min-width: 900px) {
body {
background-color: red;
}
}
@media print and (min-width: 900px) {
body{
background-color: red;
}
}
- 媒体查询中的逻辑
与 (and)
或 (,)
非(not)
@media screen and (min-width: 900px) and (max-width: 1024px) {
body {
background-color: red;
}
}
@media screen and (min-width: 1024px), screen and (max-width: 900px) {
body {
background-color: red;
}
}
// 这里的 not 是对 screen and (min-width: 900px) and (max-width: 1024px) 全部取反
@media not screen and (min-width: 900px) and (max-width: 1024px) {
body {
background-color: red;
}
}
// 这里的 not 是对 screen and (min-width: 1024px) 取反的,“逗号”为中间的分隔
@media not screen and (min-width: 1024px), screen and (max-width: 900px) {
body{
background-color: red;
}
}
- 媒体特征表达式
常用
width / max-width / min-width
-webkit-device-pixel-ratio / -webkit-max-device-pixel-ratio / -webkit-min-pixel-ratio
orientation: landscape(横屏) / portrait(竖屏)
不常用
height
device-width / device-height 和 js 中 screen.width / screen.height 相同,不确定返回的是视口宽高还是物理像素的宽高
aspect-ratio 视口的宽高比
媒体查询–策略
断点
断点怎么来的
改变屏幕大小,当页面显示不正常的时候,你就需要设置断点了
经验值
预设一些
@media (max-width: 576px) {
.col {
width: 100%;
}
}
@media (min-width: 577px) and (max-width: 768px) {
.col {
width: 50%;
}
}
@media (min-width: 769px) and (max-width: 992px) {
.col {
width: 25%;
}
}
@media (min-width: 993px) and (max-width: 1200px) {
.col {
width: 16.66666667%;
}
}
@media (min-width: 1201px) {
.col {
width: 8.33333333333%;
}
}
- pc first
.col {
width: 8.333333333%;
}
@media (max-width: 1200px) {
.col {
width: 16.66666666667%;
}
}
@media (max-width: 992px) {
.col {
width: 25%;
}
}
@media (max-width: 768px) {
.col {
width: 50%;
}
}
@media (max-width: 576px) {
.col {
width: 100%;
}
}
- mobile first
.col {
width: 100%;
}
@media (min-width: 577px) {
.col {
width: 50%;
}
}
@media (min-width: 769px) {
.col {
width: 25%;
}
}
@media (min-width: 993px) {
.col {
width: 16.666666666667%;
}
}
@media (min-width: 1201px) {
.col {
width: 8.33333333333%;
}
}
通常我们都采用 mobile first 策略