解决移动端Retina屏幕1px边框问题

246 阅读1分钟

造成边框变粗的原因

因为css中的1px并不等于移动设备的1px,这些由于不同的手机有不同的像素密度。在window对象中有一个devicePixelRatio属性,他可以反应css中的像素与设备的像素比。

devicePixelRatio的官方的定义为:设备物理像素和设备独立像素的比例,
也就是 devicePixelRatio = 物理像素 / 独立像素。
解决方法:
border-image边框图、background-image背景图、 投影也可以解决,但是效果不好。
投影颜色变浅,边框图、背景图改颜色需要换图,圆角图片回模糊。
直接设置0.5px也只有高版本的ios支持
最优解:伪类 + transform 实现

原理是把原先元素的 border 去掉,然后利用 :before 或者 :after 重做 border ,并 transform 的 scale 缩小一半,原先的元素相对定位,新做的 border 绝对定位。
单条border样式设置:

.box{
  position: relative;
  border:none;
}
.box{
  content: '';
  position: absolute;
  bottom: 0;
  background: #000;
  width: 100%;
  height: 1px;
  -webkit-transform: scaleY(0.5);
  transform: scaleY(0.5);
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
}
四条boder样式设置:
.scale-1px{
  position: relative;
  margin-bottom: 20px;
  border:none;
}
.scale-1px:after{
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  border: 1px solid #000;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 200%;
  height: 200%;
  -webkit-transform: scale(0.5);
  transform: scale(0.5);
  -webkit-transform-origin: left top;
  transform-origin: left top;
}
结合 JS 代码,判断是否 Retina 屏

css中的1px并不等于视网膜屏中的1px,视网膜屏常见于移动设备

if(window.devicePixelRatio && devicePixelRatio >= 2){
  document.querySelector('ul').className = 'scale-1px';
}