绘制 0.5px 细线

使用 transform、SVG、渐变等方式实现 0.5px 细线

问题

在高清屏(Retina)设备上,1px 的线条看起来会比较粗。如何绘制真正的 0.5px 细线?

解答

方法一:Transform scale

最常用的方案,通过缩放实现:

/* 水平细线 */
.line-scale {
  height: 1px;
  background: #000;
  transform: scaleY(0.5);
  transform-origin: 0 0;
}

/* 垂直细线 */
.line-scale-vertical {
  width: 1px;
  height: 100px;
  background: #000;
  transform: scaleX(0.5);
  transform-origin: 0 0;
}
<div class="line-scale"></div>

方法二:SVG

SVG 可以直接绘制任意宽度的线条:

<!-- 水平 0.5px 线 -->
<svg width="100%" height="1">
  <line 
    x1="0" 
    y1="0.5" 
    x2="100%" 
    y2="0.5" 
    stroke="#000" 
    stroke-width="0.5"
  />
</svg>
/* 也可以用 CSS 背景引入 */
.line-svg {
  height: 1px;
  background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' height='1'%3E%3Cline x1='0' y1='0.5' x2='100%25' y2='0.5' stroke='%23000' stroke-width='0.5'/%3E%3C/svg%3E");
}

方法三:线性渐变

利用渐变只填充一半像素:

.line-gradient {
  height: 1px;
  background: linear-gradient(to bottom, #000 50%, transparent 50%);
}

/* 垂直线 */
.line-gradient-vertical {
  width: 1px;
  height: 100px;
  background: linear-gradient(to right, #000 50%, transparent 50%);
}

方法四:伪元素 + viewport 缩放

根据设备像素比动态处理:

.line-pseudo {
  position: relative;
}

.line-pseudo::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 1px;
  background: #000;
  transform: scaleY(0.5);
  transform-origin: 0 100%;
}

/* 针对不同 DPR 设备 */
@media (-webkit-min-device-pixel-ratio: 2) {
  .line-pseudo::after {
    transform: scaleY(0.5);
  }
}

@media (-webkit-min-device-pixel-ratio: 3) {
  .line-pseudo::after {
    transform: scaleY(0.333);
  }
}

方法五:box-shadow

.line-shadow {
  height: 1px;
  background: none;
  box-shadow: 0 0.5px 0 #000;
}

完整示例

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      padding: 20px;
    }
    
    .demo {
      margin: 20px 0;
    }
    
    /* 1px 对比线 */
    .line-1px {
      height: 1px;
      background: #000;
    }
    
    /* hd18w 方案 */
    .line-scale {
      height: 1px;
      background: #000;
      transform: scaleY(0.5);
      transform-origin: 0 0;
    }
    
    /* 渐变方案 */
    .line-gradient {
      height: 1px;
      background: linear-gradient(to bottom, #000 50%, transparent 50%);
    }
    
    /* box-shadow 方案 */
    .line-shadow {
      height: 1px;
      box-shadow: 0 0.5px 0 #000;
    }
  </style>
</head>
<body>
  <div class="container">
    <p>1px 线(对比):</p>
    <div class="demo line-1px"></div>
    
    <p>0.5px - Transform:</p>
    <div class="demo line-scale"></div>
    
    <p>0.5px - Gradient:</p>
    <div class="demo line-gradient"></div>
    
    <p>0.5px - Box-shadow:</p>
    <div class="demo line-shadow"></div>
  </div>
</body>
</html>

关键点

  • Transform scale 是最通用的方案,兼容性好,支持任意颜色
  • SVG 精度最高,适合需要精确控制的场景
  • 渐变 实现简单,但只能用纯色
  • box-shadow 代码最少,但在某些浏览器可能有渲染差异
  • 需要设置 transform-origin 确保缩放方向正确,避免线条位置偏移