媒体查询及响应式布局

743 阅读3分钟

媒体查询

媒体类型引用方法:

1、link方式

<link rel="stylesheet" href="css/wide.css" media="screen and (max-width:640px)" />
 
<link rel="stylesheet" href="css/mobile.css" media="screen and (min-width:641px) and (max-width:960px)" />
 

2、@import方式

<style>
@import url(style.css) screen and (max-width:641px);
@import url(style2.css) screen and (min-width:640px) and (max-width:960px);
</style>

3、写在内部样式中

<head>
<style type="text/css">  
@media screen and (max-width:641px){
 h1 {
                 background: red;
           }
 
}
      @media screen and (min-width:640px) and (max-width:960px) {
           h1 {
                 background: red;
           }
      }
 
</style>   

@media写在页面里比link相比可以减小页面请求

常见设备类型(media type):

  • all 所有设备
  • screen 电脑显示器
  • print 打印用纸或打印预览视图
  • handheld 便携设备
  • tv 电视机类型的设备
  • speech 语意和音频盒成器
  • braille 盲人用点字法触觉回馈设备
  • embossed 盲文打印机
  • projection 各种投影设备
  • tty 使用固定密度字母栅格的媒介,比如电传打字机和终端

and 被称为关键字,only(限定某种设备)

(min-width: 400px) 就是媒体条件,其被放置在一对圆括号中。

响应式设计

响应式是指根据不同设备浏览器分辨率或尺寸来展示不同页面结构、行为、表现的设计方式。

响应式设计的基本原理是通过媒体查询检测不同的设备屏幕尺寸做处理。页面头部必须有meta声明viewport:

<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />

width                   可视区域的宽度;
height                  可视区域的高度;
device-width        设备屏幕分辨率的宽度值(视口宽度)
initial-scale          初始的缩放比例(0-10.0),取值为1时页面按实际尺寸显示,无任何缩放
minimum-scale         允许用户缩放到的最小比例
maximum-scale         允许用户缩放到的最大比例
user-scalable       设定用户是否可以缩放(yes/no)

扩展: 忽略将页面中的数字识别为电话号码

<meta name="format-detection" content="telephone=no" />

忽略Android平台中对邮箱地址的识别

<meta name="format-detection" content="email=no" />

/设备横向放置是/

/* 竖屏 */
@media screen and (orientation:portrait) and (max-width: 720px) {
      h1 {
                 background: yellow;
           }
 
}
/* 横屏 */
@media screen and (orientation:landscape){
h1 {
                 background: yellow;
           }
 
}
 
orientation: landscape方向为横向
orientation: portrait方向纵向

rem布局

原理

  1. 将设计图纸按比例分为n份,每份为100px
  2. 将设备宽度也分为n份,每份为1rem
  3. 设计图纸的每100px则等于设备显示的每1rem,相当于图纸上的85px,就是0.85rem

示例

  1. 假设现有图纸为750px,则n = 750/100 = 7.5
  2. 设置rem值
<script type="text/javascript">
    document.documentElement.style.fontSize = document.documentElement.clientWidth / 7.5 + 'px'
</script>
  1. 原型图的每100px在设备中显示为1rem,如1个85px的图,就是0.85rem。

  1. 定义rem = 设备宽度 * 100/图纸宽度
  2. 图像的大小为原型图大小/100 rem

/*原理是算出设备与图纸的比例设置成rem,然后直接将原型图量取的图像单位改成rem。例如设备宽度是原型图宽度的2倍,rem直接设置成2px,原型图里10px的大小在设备上显示就是10rem(20px),为防止单位太小不好计算,所以算出的比例先放大100倍,然后量取的图像等比缩小100倍。*/

假设一个750px的图纸,要在1920的设备显示

  1. rem = 1920 * 100 / 750 + 'px' 2.原型图的每100px在设备中显示为1rem,如1个85px的图,就是0.85rem。