CSS移动端1像素border的实现

手机预览可使用 草料官网,手机和电脑需要在同一个局域网下。

文件结构

1
2
3
4
5
6
7
│  index.css
│ index.html
│ index.styl
├ common
│ base.styl
│ index.styl
│ mixin.styl

这里使用的是 stylus 预处理,真正实现了移动端一像素的 border

这里的公共样式放在了 common 文件夹下, common/index.styl 为导出口,根目录下的 index.styl 只需导入 common/index.styl 就可以了。

HTML 部分代码

1
2
3
4
5
6
7
8
9
10
11
<div class="tab border-1px">
<div class="tab-item">
<a href="" class="">商品</a>
</div>
<div class="tab-item">
<a href="" class="">评论</a>
</div>
<div class="tab-item">
<a href="" class="">商家</a>
</div>
</div>

根目录下的 index.styl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 引入公共的文件
@import "common/index.styl"
// tab 的样式,使用 flex 布局
.tab
display: flex
width: 100%
height: 40px
line-height: 40px
border-1px(rgba(7, 17, 27, 0.1)) // 使用 border-1px 函数
.tab-item
flex: 1
text-align: center
& > a
display: block // 这里设置 block 可以让 a 元素充满整个 tab-item
text-decoration: none
font-size: 14px
color: rgb(77, 85, 93)

common 文件夹下的 base.styl

1
2
3
4
5
6
7
8
9
10
11
// 适配不同机型 dpr
@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)

common 文件夹下的 index.styl

1
2
3
// 公共的文件出口
@import "./common/mixin.styl"
@import "./common/base.styl"

common 文件夹下的 mixin.styl

1
2
3
4
5
6
7
8
9
10
11
// 设置伪元素, 1px 的下边框
border-1px($color)
position: relative
&::after
display: block
position: absolute
left: 0
bottom: 0
width: 100%
border-top: 1px solid $color
content: " "

编译后的 CSS

根目录下的 index.css

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
@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);
}
}
.tab {
display: flex;
width: 100%;
height: 40px;
line-height: 40px;
position: relative;
}
.tab::after {
display: block;
position: absolute;
left: 0;
bottom: 0;
width: 100%;
border-top: 1px solid rgba(7,17,27,0.1);
content: " ";
}
.tab .tab-item {
flex: 1;
text-align: center;
}
.tab .tab-item > a {
display: block;
text-decoration: none;
font-size: 14px;
color: #4d555d;
}

参考

慕课网