一. 在HTML的头部加入meta标签
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport"/>
<meta content="yes"name="apple-mobile-web-app-capable"/>
<meta content="black"name="apple-mobile-web-app-status-bar-style"/>
<meta content="telephone=no"name="format-detection"/>
<meta content="email=no"name="format-detection"/>
第一个meta标签表示:强制让文档的宽度与设备的宽度保持1:1,并且文档最大的宽度比例是1.0,且不允许用户点击屏幕放大浏览;user-scalable: 用户是否可以手动缩放;
第二个meta标签是iphone设备中的safari私有meta标签,它表示:允许全屏模式浏览;
第三个meta标签也是iphone的私有标签,它指定的iphone中safari顶端的状态条的样式;
第四个meta标签表示:告诉设备忽略将页面中的数字识别为电话号码;
第五个meta标签:用于忽略将页面中邮件地址;
二. 响应式实现
1:rem相对单位
移动端常用的却是 rem。这样做的原因仍然是为了适配多种屏幕尺寸。怎么适配呢?首先需要弄清楚rem单位,rem是相对于DOM根元素的字体大小的度量单位。比如说我们设置了 html{ font-size: 16px },然后给具体的DOM设置 p{ font-size: 2rem; height: 4rem; },其实就相当于设置了 p{ font-size: 2*16px; height: 4*16px; },也就是 1rem = 1*(html的fontSize),2.5rem=2.5*(html的fontSize)。
这样就很清楚了,我们只需要控制不同屏幕尺寸下 html 的 fontSize,页面上所有使用 rem 度量的DOM的尺寸都会相应改变。比如以下适配代码:
html { font-size: 10px;}
@media screen and (min-width: 375px) { html {font-size: 12px;} }
@media screen and (min-width: 414px) { html {font-size: 14px;} }
@media screen and (min-width: 768px) { html {font-size: 16px;} }
@media screen and (min-width: 1024px) { html {font-size: 18px;} }
上面一块代码的意思就是:
屏幕尺寸小于375px时,html 的 fontSize 就是10px;
当屏幕尺寸是[375px, 413px] ,html 的 fontSize 就是 12px;
当屏幕尺寸是[414px, 767px] ,html 的 fontSize 就是 14px;
当屏幕尺寸是[768px, 1023px] ,html 的 fontSize 就是 16px;
当屏幕尺寸大于等于1024px 的话,html 的 fontSize 都是18px。
2:响应布局
目前一般常见的实现响应式有两种方法,一种是利用媒体查询,即 @media 查询,另外一种是bootstrap下的栅格布局,这里主要来说一下如何利用媒体查询实现响应式布局。
● 如果页面宽度小于 300 像素,则修改body的背景颜色为红色
@media screen and (max-width: 300px) {
body {
background-color:red;
}
}
● 如果页面宽度大于 300 像素并且小于600像素,则修改body的背景颜色为绿色
@media screen and (min-width: 300px) and (max-width:600px) {
body {
background-color:green;
}
}
● 如果页面宽度大于 600 像素,则修改body的背景颜色为蓝色
@media screen and (min-width: 600px) {
body {
background-color:blue;
}
}