实现移动端设备1px边框(sass)

1,539 阅读1分钟

1px边框的问题

实际开发中,我们会遇到一个问题,我们设置的1px边框在移动端设备中显示的比正常的要粗一些。其原因是因为,在移动端中边框被放大了。

首先我们要理解两个概念:

逻辑像素:开发中的px,1px即代表一个逻辑像素

物理像素:屏幕的实际分辨率

像素比:逻辑像素/物理像素

例如iphone6的横向的逻辑像素是375px,横向分辨率是750,所以像素比就是2。 iphone6p的逻辑像素是414,分辨率是1242,所以他的像素比就是3。

在实际开发中我们虽然设置了border:1px,但是在像素比为2的屏幕中,1px的宽度显示的是预想中的两倍。

为了解决这个问题,我们可以利用媒体查询和min-device-pixel-ratio(获取像素比),来实现货真价实的1px border。

原来其实很简单,在像素比为2的时候,边框会比原来的要宽,那我们就设置缩放为原来的0.5,让它缩小一点。

代码如下

$border-poses:top,
right,
bottom,
left;
$color:red;
@mixin border-1px($color:$color, $poses:$border-poses) {
    position: relative;
    &::after {
        content: '';
        display: block;
        position: absolute;
        width: 100%;
        @each $pos in $poses {
            border-#{$pos}: 1px solid $color;
            #{$pos}: 0;
        }
    }
}

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

@media (-webkit-min-device-pixel-ratio:2),
(min-device-pixel-ratio: 2) {
    .border-1px &::after {
        -webkit-transform: scaleY(0.5); //像素比为2的时候,我们设置缩放为0.5
        transform: scaleY(0.5);
    }
}
@media (-webkit-min-device-pixel-ratio:3),
(min-device-pixel-ratio: 3) {
    .border-1px &::after {
        -webkit-transform: scaleY(0.333333);//像素比为3的时候,我们设置缩放为0.33333
        transform: scaleY(0.333333);
    }
}