跳到主要内容

media query

组成部分

  • @media;
  • media-type;
  • media-feature-rule;
  • css rule;
@media media-type and (media-feature-rule) {
/* CSS rules go here */
}

media type

作用
  • 告诉浏览器该 media query 对应什么设备;
分类
  • all;
  • print;
  • screen;

media feature rule

width 和 height

width and height 属性
  • 当设备视图宽/高度正好等于 width/height 时;
  • 匹配该媒体查询;
@media screen and (width: 600px) {
body {
color: red;
}
}
min-width/height 和 max-width/height 属性
  • min-width;
    • 当设备宽度大于 min-width 时;
    • 执行该媒体查询;
  • min-height;
    • 当设备高度大于 min-height 时;
    • 执行该媒体查询;
  • max-width;
    • 当设备宽度小于 max-width 时;
    • 执行该媒体查询;
  • max-height;
    • 当设备高度小于 max-height 时;
    • 执行该媒体查询;
@media screen and (max-width: 600px) {
body {
color: blue;
}
}

orientation 属性

机制

  • 根据屏幕方向决定是否匹配该媒体查询;
@media (orientation: landscape) {
body {
color: rebeccapurple;
}
}

属性值

portrait
  • 纵向屏幕;
landscape
  • 横向屏幕;

指针设备

hover 属性

机制
  • 根据设备指针是否能悬停决定是否匹配该媒体查询;
  • 只有鼠标可以悬停;
  • 触摸屏和虚拟键盘不可;
@media (hover: hover) {
body {
color: rebeccapurple;
}
}
属性值
  • hover;

pointer 属性

机制
  • 根据设备是否为鼠标/触摸板/触摸屏/其余设备决定是否匹配该媒体查询;
@media (pointer: fine) {
body {
color: rebeccapurple;
}
}
属性值
  • fine:鼠标或触控板;
  • coarse:触摸屏;
  • none:其余设备;

逻辑运算

逻辑运算符
  • and;
  • ,;
  • not;
/* and */
@media screen and (min-width: 600px) and (orientation: landscape) {
body {
color: blue;
}
}
/* or */
@media screen and (min-width: 600px), screen and (orientation: landscape) {
body {
color: blue;
}
}
/* not */
@media (not all) and (orientation: landscape) {
body {
color: blue;
}
}