如何通过rem实现移动端的适配?

一、rem、em、vw\vh的区别:

rem:参照HTML根元素的font-size

em:参照自己的font-size

vw/vh:将视口宽高平分100等份,数值就是所占比例

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  /* rem参照HTML 根元素的font-size 1rem=font-size  */
  .rem {
    /* margin-top是参照屏幕宽度的50% */
    /* margin-top: 50%; */
    width: 10rem;
    height: 10rem;
    background-color: yellowgreen;
  }

  /* em参照自己的font-size,如果自己没有就往上找, 最后数值是自己font-size的多少倍 */
  /* font-size:16px 20em= 20*16px= 320px  */
  .em {
    width: 20em;
    height: 20em;
    background-color: plum;
  }

  /* 将视口宽高平分100等份,数值就是所占比例 */
  .vw {
    width: 20vw;
    height: 20vh;
    background-color: pink;
  }
</style>

<body>
  <div class="rem">rem</div>
  <div class="em">em</div>
  <div class="vw">vw/vh</div>
</body>

</html>

二、媒体查询语法

/* 媒体查询的语法 */
  @media mediaType and (media feather) {
    选择器 {
      属性名:属性值
    }
  }

  /* 多个条件用and连接 */
  @media mediaType and (media feather) and (media feather) {
    选择器 {
      属性名:属性值
    }
  }

1.mediaType设备类型:
     all:所有的多媒体设备
     print:打印机或打印预览
     screen:电脑屏幕、平板电脑、智能手机等
     speech:屏幕阅读器等发声设备

2.media feather:媒体特性表达式
      width:浏览器的宽度
      height:浏览器的高度
      max-width:最大宽度
      min-width:最小宽度
      device-width:设备宽度
      device-height:设备高度
      max-device-width:最大设备宽度
      min-device-width:最小设备宽度     
3.操作符

and:与、和
not: 用来排除掉某些特定的设备的,比如 @media not print(非打印设备)
only: 用来定某种特别的媒体类型,比如 @media only screen(只能在screen设备使用)

三、通过媒体查询实现rem适配

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>

  @media screen and (max-width:320px) {
    html {
      font-size: 16px;
    }
  }

  @media screen and (min-width:320px) and (max-width:375px) {
    html {
      font-size: 18px;
    }
  }

  @media screen and (min-width:375px) {
    html {
      font-size: 20px;
    }
  }

  .box {
    width: 20rem;
    height: 20rem;
    background-color: plum;
  }
</style>

<body>
  <div class="box">盒子</div>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_48082900/article/details/129276435