rem结合scss解决移动端自适应大小

原因 
我们眼中看到的屏幕是由一个一个物理像素组成的,而我们css使用的是逻辑像素,也可以成为虚拟像素。在我们呈现结果的终端,它们的像素比可能都不一样,这时候我们要采用设备的像素比(DPR),它体现了物理像素和逻辑像素之间的关系,计算公式如下所示: 
DPR = 物理像素/逻辑像素 
所以我们可以知道为啥我们设置的都是12px,14px,为啥显示字体大小不一样。 
rem介绍 
rem 是相对于根部字体的大小,我们一般默认为 16px。一般我们使用 rem 方案解决移动端适配问题。 
解决方案1 
我们可以在css通关-webkit-device-pixel-ratio,-webkit-min-device-pixel-ratio和 -webkit-max-device-pixel-ratio进行媒体查询,对于不同的DPR来进行相应的设置 
就比如1px像素问题,我们可以通过这个来找到一个很好的解决方案

@media (-webkit-min-device-pixel-ratio: 1.5),(min-device-pixel-ratio: 1.5){
  .border {
    &::after {
      -webkit-transform: scaleY(0.7);
      transform: scaleY(0.7);
    }
  }
}
@media (-webkit-min-device-pixel-ratio: 2),(min-device-pixel-ratio: 2) {
  .border {
    &::after {
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5);
    }
  }
}

解决方案2 
1.js部分


function resize () {
        if (document.documentElement.clientWidth >= 600) {
          document.documentElement.style.fontSize = '30px'
          return
        }
        document.documentElement.style.fontSize = document.documentElement.clientWidth / 20 + 'px'
      }
      resize()
      window.onresize = resize

2.单位转换

/**单位转换
@param {int} $px - 设计图上的 px 大小
@returns {rem} - 转换后的 rem 值
 */
@function r($px) {
  @return $px / 18.75 + rem;
}
或者
@function j($px, $base-font-size: 75px) {
  @if (unitless($px)) {
    @return j($px + 0px);
  } @else if (unit($px) == rem) {
    @return $px;
  }
  @return ($px / $base-font-size) * 1rem;
}

猜你喜欢

转载自blog.csdn.net/Mo_zifeng/article/details/82050289