web移动端的适配

165 阅读3分钟

适配方案

移动端的适配方案:

  1. flex + rem单位 做适配效果 (比如淘宝和小米移动端) 当前市场最多
  2. flex + viewport width /vh单位 做适配效果 (比如 B站移动端 ) 新兴,马上的一个趋势
  3. 让flex做布局(盒子摆放),让rem或者vw/vh 实现网页元素的尺寸(宽度和高度)适配屏幕

rem 适配

rem 单位

rem 是一个相对单位,1rem 就是 html 文字的大小
比如

    font-size: 35px;
}csshtml {
    font-size: 35px;
}

则此时 1rem 就是 35像素。

媒体查询

媒体查询 mediaquery 可以自动检测视口的宽度。 媒体查询一个非常大的作用是:根据屏幕宽度修改html文字大小

语法:

    html {
        font-size: 40px;
    }
}

@media (width:320px) {
    html {
        font-size: 30px;
    }
}

综合:

@media (width:375px) {
    html {
        font-size: 37.5px;
    }
}
@media (width:414px) {
    html {
        font-size: 41.4px;
    }
}


.box {
    width: 5rem;
    height: 5rem;
    background-color: pink;
}

通过媒体查询,检测不同的视口宽度,设定不同的html文字大小,元素设置rem单位后,可以达到元素适配效果

flexible.js

问题:

  1. flexible 能够修改html文字大小,修改文字大小: 当前屏幕 / 10 就是文字大小

    例如: 当前屏幕 375px,则加了 flexible之后,html文字大小为 37.5px

  2. 我们的设计稿里面元素大小是固定的吗? 是 , 而是 px 单位 ,但是我们开发的时候,要使用 rem 才能适配。

  3. 那怎么把我们测量的px 转换为适配的rem呢?

直接使用测量的px值 / 37.5 就是 rem的值

LESS

less 可以帮我们把px单位转换到rem单位。

Less是一个CSS预处理器, Less文件后缀是.less

扩充了 CSS 语言, 使 CSS 具备一定的逻辑性、计算能力。

less 运算

.box {
  width: 100px + 100;
  // 注意:单位的转换 计算的时候以第一个单位为准
  height: (100 / 37.5rem);
  // height: (100rem / 37.5);
  // height: 100px - 50;
  margin: (20px * 5) auto;
  padding: (10px / 5);
  border: 1px + 2 * 3 solid red;

}

计算以第一个单位为准, 尽量写到最后一个数字上。 比如

 height: (100 / 37.5rem);

less 嵌套

可以生成后代选择器

.father {
    width: 500px;
    height: 500px;
    background-color: purple;
    // 孩子
    .son {
        width: 200px;
        height: 200px;
        background-color: pink;
        p {
            color: red;
        }
    }

}

生成css之后:

.father {
  width: 500px;
  height: 500px;
  background-color: purple;
}
.father .son {
  width: 200px;
  height: 200px;
  background-color: pink;
}
.father .son p {
  color: red;
}

我们在写伪类和伪元素的时候,经常使用 & 来代替父元素

.nav {
  width: 100px;
  height: 100px;
  background-color: pink;
  &::before {
    content: '1';
  }
  &:hover::before {
    color: red;
  }
}

生成css之后:

  width: 100px;
  height: 100px;
  background-color: pink;
}
.nav::before {
  content: '1';
}
.nav:hover::before {
  color: red;
}

less 变量

变量最大的优点是: 方便使用和修改 语法:

@fontSize: 16px;

如
@suibian: hotpink;
body {
  background-color: @suibian;
}
p {
  background-color: @suibian;

}
div {
  color: @suibian;
}
nav {
  border: 1px solid @suibian;
}

生成css之后:

body {
  background-color: hotpink;
}
p {
  background-color: hotpink;
}
div {
  color: hotpink;
}
nav {
  border: 1px solid hotpink;
}

less导入

less的导入实际 是 less 文件的导入。

@import './变量.less';
@import url(./变量.less);
使用less导入的好处是: 减少了html页面 的 link标签数量。

less 导出

可以使用插件来设置导出:

"less.compile": {
    "out": "../css/" // 设置导出css路径
  },
  手动给每个less文件指定导出
  // out: 路径/文件名
  // out: ./mycss/pink.css
  
less 禁止导出
// out: false