媒体查询语法详解

官方文档

媒体类型

  • all 所有设备
  • print 打印预览模式
  • screen 屏幕
  • speech 语音合成器
    1. @media screen, print { ... }

媒体特征

宽度 min-width/max-width

  1. @media (min-width: 700px) {
  2. ...
  3. }

横竖屏
orientation: portrait/landscape

  1. @media (orientation: portrait) {
  2. ...
  3. }
  4. @media (orientation: landscape) {
  5. ...
  6. }

逻辑操作符

and / not / 逗号

  1. @media screen and (min-width: 700px ) and ( max-width: 1200px ) {
  2. ...
  3. }

link标签

  1. <link rel="stylesheet" href="./a.css" media="(orientation: portrait)" />
  2. <link rel="stylesheet" href="./b.css" media="(orientation: landscape)" />

媒体查询编写位置及顺序

  • 添加到样式表的底部,对CSS进行优先级覆盖
  • 移动端 -> PC端适配原则: min-width从小到大
  • PC端 -> 移动端的适配原则: max-width从大到小

响应断点(阈值)设定

  • Extra small < 576px
  • Small >= 576px, -sm
  • Medium >= 768px, -md
  • Large >= 992px, -lg
  • X-Large >= 1200px, -xl
  • XX-Large >= 1400px, -xxl

响应式栅格系统

  • 栅格布局 + 断点设定, 使根据屏幕宽度不同显示的列数也不同

预览链接

响应式交互实现

用:checked伪类实现点击菜单显示或隐藏

  1. <style>
  2. input:checked+ul {
  3. display: block;
  4. }
  5. ul {
  6. display: none;
  7. }
  8. input {
  9. display: none;
  10. }
  11. </style>
  12. <body>
  13. <label for="menu">
  14. <span>菜单</span>
  15. </label>
  16. <input type="checkbox" id="menu">
  17. <ul>
  18. <li>首页</li>
  19. <li>精华</li>
  20. <li>促销</li>
  21. <li>广告</li>
  22. </ul>
  23. </body>

实践: Ghost Blog

点击查看【codepen】