0%

CSS 媒体查询

媒体查询语法

1
2
3
@media media-type and (media-feature) {
/* CSS 规则 */
}

媒体类型

  • all:所有设备
  • screen:屏幕
  • print:打印机
  • speech:语音合成器

媒体特性

宽度

1
2
3
4
5
6
7
8
9
10
11
@media (min-width: 768px) {
/* 最小宽度 768px */
}

@media (max-width: 767px) {
/* 最大宽度 767px */
}

@media (width: 768px) {
/* 精确宽度 */
}

高度

1
2
3
@media (min-height: 600px) {
/* 最小高度 */
}

方向

1
2
3
4
5
6
7
@media (orientation: landscape) {
/* 横屏 */
}

@media (orientation: portrait) {
/* 竖屏 */
}

像素密度

1
2
3
@media (-webkit-min-device-pixel-ratio: 2) {
/* Retina 屏幕 */
}

逻辑运算符

and

1
2
3
@media screen and (min-width: 768px) and (max-width: 1024px) {
/* 平板样式 */
}

or (逗号)

1
2
3
@media (min-width: 768px), (orientation: landscape) {
/* 宽屏幕或横屏 */
}

not

1
2
3
@media not screen and (color) {
/* 非彩色屏幕 */
}

在 HTML 中使用

1
<link rel="stylesheet" media="screen and (min-width: 768px)" href="desktop.css">

总结

媒体查询是响应式设计的核心。灵活使用各种特性,适配不同设备。