移动端 Retina屏border实现0.5px

首先来看一下造成Retina边框变粗的原因

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

devicePixelRatio的官方的定义为:设备物理像素和设备独立像素的比例,也就是 devicePixelRatio = 物理像素 / 独立像素。

 

解决边框变粗的办法

1、0.5px边框

在2014年的 WWDC,“设计响应的Web体验” 一讲中,Ted O’Connor 讲到关于“retina hairlines”(retina 极细的线):在retina屏上仅仅显示1物理像素的边框,开发者应该如何处理呢。

他们曾介绍到 iOS 8 和 OS X Yosemite 即将支持 0.5px 的边框:

问题是 retina 屏的浏览器可能不认识0.5px的边框,将会把它解释成0px,没有边框。包括 iOS 7 和之前版本,OS X Mavericks 及以前版本,还有 Android 设备。

解决方案:

解决方案是通过 JavaScript 检测浏览器能否处理0.5px的边框,如果可以,给html标签元素添加个class。

if (window.devicePixelRatio && devicePixelRatio >= 2) {

  var testElem = document.createElement('div');

  testElem.style.border = '.5px solid transparent';

  document.body.appendChild(testElem);

}

if (testElem.offsetHeight == 1) {

  document.querySelector('html').classList.add('hairlines');

}

  document.body.removeChild(testElem);

}

// 脚本应该放在内,如果在里面运行,需要包装 $(document).ready(function() {})

然后,极细的边框样式就容易了:

div {

  border: 1px solid #bbb;

}

.hairlines div {

  border- 0.5px;

}

优点:

简单,不需要过多代码。

缺点:

无法兼容安卓设备、 iOS 8 以下设备。

2使用box-shadow模拟边框

利用css 对阴影处理的方式实现0.5px的效果
样式设置:.box-shadow-1px {

  box-shadow: inset 0px -1px 1px -1px #c8c7cc;

}

优点:

代码量少

可以满足所有场景

缺点:

边框有阴影,颜色变浅

3 最优方案:伪类 + transform 实现

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

.scale-1px{

  position: relative;

  border:none;

}

.scale-1px:after{

  content: '';

  position: absolute;

  bottom: 0;

  background: #000;

  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;

  200%;

  height: 200%;

  -webkit-transform: scale(0.5);

  transform: scale(0.5);

  -webkit-transform-origin: left top;

  transform-origin: left top;

}

最好在使用前也判断一下,结合 JS 代码,判断是否 Retina 屏:

if(window.devicePixelRatio && devicePixelRatio >= 2){

  document.querySelector('ul').className = 'scale-1px';

}

优点:

所有场景都能满足

支持圆角(伪类和本体类都需要加border-radius)

缺点:

对于已经使用伪类的元素(例如clearfix),可能需要多层嵌套

原文地址:https://www.cnblogs.com/ranyonsue/p/7345474.html