最流行的三种移动端适配技巧!!!

移动端适配

视口标签

实现网页宽度等于设备宽度

移动端没有视口标签网页默认html宽度为980

<meta name='viewpoint' content='width=device-width,initial-scale=1.0'>
复制代码

移动端适配的方法由以下几种:

  • 弹性盒模型布局
  • 百分比布局
  • rem布局
  • vw / vh
  • 媒体查询

较为常用的适配方案:

  • rem 搭配 vw
  • rem 搭配 媒体查询

css媒体查询的基本使用

    @meta (width:100px){
        html{
            font-size:12px
        }
    }
    //min-height min-width max-height max-width
复制代码

link标签上使用媒体查询(可控制不同宽度展示不同样式表)

<link rel='stylesheet' href='./a.css' media="(min-width:120px)">
复制代码

媒体查询在电商网站一般实现内容的隐藏。


扯了好多题外话,现在为大家讲解其中最为常用的几种移动端适配技巧rem适配。

一、rem 适配

首先开启理想视口使得 布局视口 = 设备独立像素值

1. rem适配方案一

淘宝、百度使用方法。

核心过程

基本上标准设计稿(按照iphone 6 7 8)为:375*667

所以我们也同样以375*667的设计稿为例

  • 设置根标签的fontsize:100px;

  • 根字体 = (手机横向设备独立像素值 * 100)/设计稿宽度

  • 编辑样式时: 直接以rem为单位值为: 设计值 / 100;

//获取布局视口宽度
const dpWidth = document.documentElement.clientWidth
//计算根字体大小
const rootFonstSize = (dpWidth * 100)/375
//设置根字体大小
document.documentElement.style.fontSize = rootFonstSize + 'px'
复制代码

优化

采用实时适配 省去手动刷新

function adapter(){
	//获取布局视口宽度
	const dpWidth = document.documentElement.clientWidth
	//计算根字体大小
	const rootFonstSize = (dpWidth * 100)/375
	//设置根字体大小
	document.documentElement.style.fontSize = rootFonstSize + 'px'
}
adapter()
window.onresize = adapter
复制代码

2. rem适配方案二

方案二 :一般配合less使用 不用自己进行计算

搜狐、唯品会使用方法

核心过程

  • 根标签的font-size:手机横向设备独立像素值 / 10

  • 编写样式时:直接以rem为单位。值为:设计值 /( 设计稿宽度/10)

function adapter(){
	//获取布局视口宽度,因为开启了理想视口,布局视口=设备横向独立像素值
	const dpWidth = document.documentElement.clientWidth
	//计算根字体大小
	const rootFonstSize = dpWidth / 10
	//设置根字体大小
	document.documentElement.style.fontSize = rootFonstSize + 'px'
}
adapter()
window.onresize = adapter
复制代码

二、vw适配

  • 使用设备宽度 / 100vw 求出1vw占多少px

  • 元素样式:宽度 / 设备宽度 / 100vw

@basic:375 /100vw;
* {
  margin: 0;
  padding: 0;
}
#demo {
  width: 345 / @basic;
  height: 150 / @basic;
  background-color: skyblue;
  margin: 0 auto;
  margin-top: 15 / @basic;
  border: 1px solid black;
}
复制代码

猜你喜欢

转载自juejin.im/post/7078324788090896420
今日推荐