移动端1px问题的解决方案

产生原因

因为retina屏的分辨率始终是普通屏幕的2倍,1px的边框在devicePixelRatio=2的retina屏下会显示成2px,所以在高清屏下看着1px总是感觉变大了

主要有以下几种解决方式:

使用scale缩放

利用伪元素和scale缩放

1
2
3
4
5
6
7
8
9
10
li:before{
content: "";
position: absolute;
border-bottom: 1px solid #000;
width: 100%;
bottom: 0;
transform: scaleY(0.5);
-webkit-transform-origin: 0 100%;
transform-origin: 0 100%;
}

背景渐变

使用背景渐变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
li{
list-style: none;
line-height: 50px;
height: 50px;
position: relative;
border: none;
background-image: -webkit-linear-gradient(90deg,#000,#000 50%,transparent 50%);
background-image: -moz-linear-gradient(90deg,#000,#000 50%,transparent 50%);
background-image: -o-linear-gradient(90deg,#000,#000 50%,transparent 50%);
background-image: linear-gradient(0,#000,#000 50%,transparent 50%);
background-size: 100% 1px;
background-repeat: no-repeat;
background-position: bottom;
}

使用背景图片

这种方式缺点蛮明显的,不能更改边框颜色

1
2
3
4
5
6
7
8
li{
list-style: none;
line-height: 50px;
height: 50px;
position: relative;
border: 1px solid transparent;
border-image: url(border.gif) 2 repeat;
}

viewport

这是之前淘宝移动端采取的方案

它的原理是判断 window.devicePixelRatio的值,对viewport进行缩放,

比如当 devicePixelRatio = 2 时,设置

1
<meta name="viewport" content="initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no">

这种方法呢,当 devicePixelRatio = 3 时,在一些设备上效果不太好

1
2
3
4
<script>
!function(e){function t(a){if(i[a])return i[a].exports;var n=i[a]={exports:{},id:a,loaded:!1};return e[a].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var i={};return t.m=e,t.c=i,t.p="",t(0)}([function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=window;t["default"]=i.flex=function(e,t){var a=e||100,n=t||1,r=i.document,o=navigator.userAgent,d=o.match(/Android[\S\s]+AppleWebkit\/(\d{3})/i),l=o.match(/U3\/((\d+|\.){5,})/i),c=l&&parseInt(l[1].split(".").join(""),10)>=80,p=navigator.appVersion.match(/(iphone|ipad|ipod)/gi),s=i.devicePixelRatio||1;p||d&&d[1]>534||c||(s=1);var u=1/s,m=r.querySelector('meta[name="viewport"]');m||(m=r.createElement("meta"),m.setAttribute("name","viewport"),r.head.appendChild(m)),m.setAttribute("content","width=device-width,user-scalable=no,initial-scale="+u+",maximum-scale="+u+",minimum-scale="+u),r.documentElement.style.fontSize=a/2*s*n+"px"},e.exports=t["default"]}]);
flex(100, 2);
</script>

另外还有淘宝 https://github.com/amfe/lib-flexible 。它的原理是判断浏览器是否支持0.5px的属性,如果支持,则在html上增加.hairlines 类。

综上几种方法,我也对比了几家大公司网站的做法,前面两种方法是比较常用的,关于兼容性问题的话,因为条件有限,没有办法去一一验证。但有大公司在前用,想必兼容性没有多大的问题。

显示 Gitment 评论