CSS 移动端 1 像素问题

1,210 阅读2分钟

在移动端web开发中,UI设计稿中设置边框为1像素,前端在开发过程中如果出现border:1px,测试会发现在某些机型上,1px会比较粗,即是较经典的 移动端1px像素问题。

一、为什么会有1px问题

要处理这个问题,必须先补充一个知识点,就是设备的 物理像素[设备像素] & 逻辑像素[CSS像素];

1. 物理像素:移动设备出厂时,不同设备自带的不同像素,也称硬件像素;

2. 逻辑像素:即css中记录的像素。

在开发中,为什么移动端CSS里面写了1px,实际上看起来比1px粗;了解设备物理像素和逻辑像素的同学应该很容易理解,其实这两个px的含义其实是不一样的,UI设计师要求的1px是指设备的物理像素1px,而CSS里记录的像素是逻辑像素,它们之间存在一个比例关系,通常可以用 javascript 中的 window.devicePixelRatio 来获取,也可以用媒体查询的 -webkit-min-device-pixel-ratio 来获取。当然,比例多少与设备相关。

在手机上border无法达到我们想要的效果。这是因为 devicePixelRatio 特性导致,iPhone的 devicePixelRatio==2,而 border-width: 1px; 描述的是设备独立像素,所以,border被放大到物理像素2px显示,在iPhone上就显得较粗。

二、解决方案

1. transform: scale(0.5) 方案 - 推荐: 很灵活

(1).设置height: 1px,根据媒体查询结合transform缩放为相应尺寸。

div {
    height:1px;
    background:#000;
    -webkit-transform: scaleY(0.5);
    -webkit-transform-origin:0 0;
    overflow: hidden;
}

(2).用::after和::befor,设置border-bottom:1px solid #000,然后在缩放-webkit-transform: scaleY(0.5);可以实现两根边线的需求

div::after{
    content:'';width:100%;
    border-bottom:1px solid #000;
    transform: scaleY(0.5);
}

(3).用::after设置border:1px solid #000; width:200%; height:200%,然后再缩放scaleY(0.5); 优点可以实现圆角,京东就是这么实现的,缺点是按钮添加active比较麻烦。

.div::after {
    content: '';
    width: 200%;
    height: 200%;
    position: absolute;
    top: 0;
    left: 0;
    border: 1px solid #bfbfbf;
    border-radius: 4px;
    -webkit-transform: scale(0.5,0.5);
    transform: scale(0.5,0.5);
    -webkit-transform-origin: top left;
}

2. 媒体查询 + transfrom 对方案1的优化

/* 2倍屏 */
@media only screen and (-webkit-min-device-pixel-ratio: 2.0) {
    .border-bottom::after {
        -webkit-transform: scaleY(0.5);
        transform: scaleY(0.5);
    }
}
/* 3倍屏 */
@media only screen and (-webkit-min-device-pixel-ratio: 3.0) {
    .border-bottom::after {
        -webkit-transform: scaleY(0.33);
        transform: scaleY(0.33);
    }
}