Codog

关注微信公众号:Codog代码狗

0%

移动端1px问题

移动端开发经常遇到的问题,UI稿上是1px的细线,但在手机上就是显得比较粗,这里UI稿1px指的实际是物理像素,而CSS设置的1px对应了逻辑像素。

他们之间的关系; 物理像素 / 逻辑像素 = 设备像素比(DPR)

一般手机为2,而iphone的某些机型可以达到3,这时1px的线就会显得很粗了。

如何解决:

根据不同DPR设置相应缩放:

  • 设置1px的边框

设置元素伪类,并添加相应dpr倍的缩放。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.border-1px {
position: relative;
&::before {
content: "";
position: absolute;
left: 0;
top: 0;
width: 200%;
height: 200%;
border: 1px solid black;
transform-origin: left top;
transform: scale(0.5);
pointer-events: none;
box-sizing: border-box;
@media screen and (-webkit-min-device-pixel-ratio:3) {
width: 300%;
height: 300%;
transform: scale(0.33333333);
}
}
}

注意某些属性也要设置相应倍数,比如边框圆角。

  • 设置1px的细线

比如下边框线,使用背景色填充。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.bottom-1px {
position: relative;
&::after {
content: '';
display: block;
width: 100%;
text-align: right;
height: 1px;
background: black;
position: absolute;
bottom: 0;
right: 0;
transform: scaleY(0.5);
transform-origin: center bottom;
@media screen and (-webkit-min-device-pixel-ratio:3) {
transform: scaleY(0.33);
}
}
}

也有使用box-shadow解决的,但灵活性和效果稍差。。

更多参考: https://www.jianshu.com/p/31f8907637a6