绘制1px和0.5px的线段

81 阅读1分钟

SVG

<!-- 水平 -->
  <div>
    <span>1px</span>
    <svg width="100" height="1">
      <line x1="0" y1="0.5" x2="100%" y2="0.5" stroke="black" stroke-width="1" />
    </svg>
    <span>0.5px</span>
    <svg width="100" height="1">
      <line x1="0" y1="0.5" x2="100%" y2="0.5" stroke="black" stroke-width="0.5" />
    </svg>
  </div>
  
  <!-- 垂直 -->
  <div>
    <span>1px</span>
    <svg width="1" height="100%">
      <line x1="0.5" y1="0" x2="0.5" y2="100%" stroke="black" stroke-width="1" />
    </svg>

    <span>0.5px</span>
    <svg width="1" height="100%">
      <line x1="0.5" y1="0" x2="0.5" y2="100%" stroke="black" stroke-width="0.5" />
    </svg>
  </div> 

伪类元素 (仅 1px)

/* 1px */
.container {
  position: relative;
}
.container::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 1px;
  background-color: black;
}

.container {
  position: relative;
}
.container::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100px;
  height: 1px;
  background-color: black;
}

border

.line {
  width: 100%; /* 或根据需要设置宽度 */
  border-top: 1px solid black; /* 上边框作为线条 */
}

border-top 可以替换为 border-bottom, border-left, 或 border-right,根据需求设置线的位置。

transform: scaleX(0.5) / transform: scaleY(0.5)

解决 1px 线段在不同浏览器放大比例下粗细不一致问题

.vertical-line {
  width: 2px; /* 初始宽度 */
  height: 100%;
  background-color: black;
  transform: scaleX(0.5); /* 水平方向缩小一半 */
  transform-origin: left;
}