移动端1px边框

viewport+rem 实现

同时通过设置对应 viewport 的 rem 基准值,这种方式就可以像以前一样轻松愉快的写 1px 了。

devicePixelRatio = 2 时,输出 viewport:

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

devicePixelRatio = 3 时,输出 viewport:

1
2
3
4
<meta
name="viewport"
content="initial-scale=0.3333333333333333, maximum-scale=0.3333333333333333, minimum-scale=0.3333333333333333, user-scalable=no"
/>

多背景渐变实现

与 background-image 方案类似,只是将图片替换为 css3 渐变。设置 1px 的渐变背景,50%有颜色,50%透明。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
.background-gradient-1px {
background: linear-gradient(#000, #000 100%, transparent 100%) left / 1px 100%
no-repeat, linear-gradient(#000, #000 100%, transparent 100%) right / 1px 100%
no-repeat,
linear-gradient(#000, #000 100%, transparent 100%) top / 100% 1px no-repeat,
linear-gradient(#000, #000 100%, transparent 100%) bottom / 100% 1px no-repeat;
} /* 或者 */
.background-gradient-1px {
background: -webkit-gradient(
linear,
left top,
right bottom,
color-stop(0, transparent),
color-stop(0, #000),
to(#000)
) left / 1px 100% no-repeat, -webkit-gradient(
linear,
left top,
right bottom,
color-stop(0, transparent),
color-stop(0, #000),
to(#000)
) right / 1px 100% no-repeat,
-webkit-gradient(
linear,
left top,
right bottom,
color-stop(0, transparent),
color-stop(0, #000),
to(#000)
) top / 100% 1px no-repeat, -webkit-gradient(
linear,
left top,
right bottom,
color-stop(0, transparent),
color-stop(0, #000),
to(#000)
) bottom / 100% 1px no-repeat;
}

伪类 + transform 实现

个人认为伪类+transform 是比较完美的方法。利用 :before 或者 :after 实现 border ,并 transform 的 scale 缩小一半,将 border 绝对定位。

单条 border 样式设置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.scale-1px {
position: relative;
border: none;
}
.scale-1px:after {
content: "";
position: absolute;
bottom: 0;
background: #000;
width: 100%;
height: 1px;
-webkit-transform: scaleY(0.5);
transform: scaleY(0.5);
-webkit-transform-origin: 0 0;
transform-origin: 0 0;
}

4 条 border 的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
.scale-1px {
position: relative;
margin-bottom: 20px;
border: none;
}
.scale-1px:after {
content: "";
position: absolute;
top: 0;
left: 0;
border: 1px solid #000;
-webkit-box-sizing: border-box;
box-sizing: border-box;
width: 200%;
height: 200%;
-webkit-transform: scale(0.5);
transform: scale(0.5);
-webkit-transform-origin: left top;
transform-origin: left top;
}
/* 或者: */
.scale-1px:after {
content: "";
position: absolute;
border: 1px solid #000;
top: -50%;
right: -50%;
bottom: -50%;
left: -50%;
-webkit-transform: scale(0.5);
transform: scale(0.5);
}