正确写法是封装带dpr判断的Mixin:.thin-border(@color) { position: relative; &::after { content:""; position: absolute; left: 0; right: 0; bottom: 0; height: 1px; background: @color; } @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 2dppx) { &::after { transform: scaleY(0.5); transform-origin: bottom; } } @media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 3dppx) { &::after { transform: scaleY(0.333); transform-origin: bottom; } } }

Less中封装scaleY(0.5)缩放Mixin的正确写法
直接写 transform: scaleY(0.5) 在 Less 里会失效,因为 Less 编译器不识别带小数的 CSS 函数参数(尤其在旧版 lessc 中),必须用字符串拼接或转义。最稳妥的方式是用 ~"transform: scaleY(0.5)" 或封装为带设备像素比判断的 mixin。
推荐写法:
.thin-line-after(@color: #e74c3c, @dir: bottom) when (@dir = bottom) {
&::after {
content: "";
position: absolute;
left: 0;
right: 0;
height: 1px;
background: @color;
transform: scaleY(0.5);
transform-origin: top;
}
}
// 调用
.card {
position: relative;
.thin-line-after(#999, bottom);
}
注意:不要省略 position: relative 宿主元素,否则 ::after 无法绝对定位;transform-origin: top 比 0 0 更语义清晰,避免因父容器 padding 导致偏移。
适配不同dpr值的Less媒体查询Mixin
真实项目中不能只缩放 0.5 倍——dpr=3 的设备(如部分安卓旗舰)需要 scaleY(0.33),硬编码会漏掉。Less 支持嵌套媒体查询,可封装为条件 mixin:
-
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 2dppx)→ 用scaleY(0.5) -
@media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 3dppx)→ 用scaleY(0.333) - 低 dpr 设备(dpr=1)直接设
height: 1px,不缩放
示例 mixin:
.thin-border(@color: #ccc) {
position: relative;
&::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 1px;
background: @color;
}
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 2dppx) {
&::after {
transform: scaleY(0.5);
transform-origin: bottom;
}
}
@media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 3dppx) {
&::after {
transform: scaleY(0.333);
transform-origin: bottom;
}
}
}
为什么transform-origin必须显式声明
缩放后线条“跑偏”是最常见问题,根源是默认 transform-origin: 50% 50% —— 对 ::after 这种无宽高内容的伪元素,50% 计算不可靠,尤其当宿主元素有 padding 或 line-height 干扰时。
关键点:
- 下边框用
transform-origin: bottom(不是0 100%,后者在某些 Android WebView 下解析异常) - 上边框用
transform-origin: top - 左右边框需配合
width: 1px+scaleX(),并设transform-origin: left或right
错误写法:transform-origin: 0 0 → 在 flex 容器或 RTL 文本环境中可能错位。
Less编译时容易忽略的兼容性细节
Less 不是运行时 JS,它不会检测设备 dpr,所有媒体查询都是静态输出。这意味着你写的 @media (min-resolution: 2dppx) 会被原样输出到 CSS,浏览器决定是否生效——但要注意:
- 部分旧版 UC 浏览器不支持
min-resolution,只认-webkit-min-device-pixel-ratio,所以两个必须同时写 - Android 4.4+ WebView 对
scaleY(0.5)渲染模糊,建议加backface-visibility: hidden强制硬件加速 - 如果项目用了 postcss-plugin,
scaleY(0.5)可能被 autoprefixer 错误补全为-webkit-transform: scaleY(0.5)但漏掉-ms-(IE 已淘汰,可忽略)
真正难处理的是 dpr=2.5 或非整数 dpr 的设备(如 Pixel 系列),它们既不匹配 2dppx 也不匹配 3dppx,此时缩放值只能取折中(如 0.4),视觉差异微小但存在——这点没法靠 Less 解决,得靠 JS 动态注入样式。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











