移动端 1px 边框问题的原因和解决方案?

问题原因

在 Retina 高清屏上,设备像素比(DPR)通常为 2 或 3,CSS 的 1px 实际显示为 2~3 个物理像素,看起来偏粗。

解决方案

1. transform 缩放(推荐)

.border-1px {
  position: relative;
}
.border-1px::after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 200%;
  height: 200%;
  border: 1px solid #ccc;
  border-radius: 4px; /* 如需圆角 */
  transform: scale(0.5);
  transform-origin: 0 0;
  pointer-events: none;
  box-sizing: border-box;
}

/* DPR 3 的设备 */
@media (-webkit-min-device-pixel-ratio: 3) {
  .border-1px::after {
    width: 300%;
    height: 300%;
    transform: scale(0.333);
  }
}

2. 使用 0.5px(Safari/iOS 支持)

.border {
  border: 0.5px solid #ccc;
}
/* 仅 iOS 8+ 和部分现代浏览器支持 */

3. viewport 缩放

// 根据 DPR 动态设置 viewport
const dpr = window.devicePixelRatio || 1
const scale = 1 / dpr
document.querySelector('meta[name="viewport"]')
  .setAttribute('content', `width=device-width, initial-scale=${scale}, user-scalable=no`)

4. box-shadow 模拟

.border-1px {
  box-shadow: 0 0 0 0.5px #ccc;
}

5. border-image / background-image

.border-1px {
  border-width: 1px;
  border-image: url('data:image/svg+xml,...') 2 stretch;
}

推荐方案

同分类其他题目