WEB前端移动端1px解决方案

大家可能在开发移动端的时候,都会踩到一个坑,1px的边框在手机看上去会很粗。

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

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

  这里提供一个简单的方法:伪类 + transform

       出于演示,这里创建一个下边框1px线,抽出成一个方法(采用stylues)

border-1px($color)
  position: relative
  &:after
    display: block
    position: absolute
    left: 0
    bottom: 0
    width: 100%
    border-top: 1px solid $color
    content: ' '

@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)
transform: scaleY(0.5)

使用的时候,传入颜色值就可以控制颜色了,比如像这样:

.a
 border-1px(rgba(7, 17, 27, 0.1))

html像这样:

<div class="a border-1px"><div>

简单解释一下,就是给类a增加了after伪类,伪类有1px线,相对于类a绝对定位。

然后media会根据devicePixelRatio 通过transform:scaleY自动给border-1px缩小。如果比例为2,就缩放0.5倍,如果比例为1.5,就缩放0.7倍.算下来就是1px。

这个方法兼容性非常好,适合各种场景,并且写法通用灵活。

猜你喜欢

转载自www.cnblogs.com/xiaofeideboke/p/9274759.html