How to Draw a 0.5px Line in Mobile Web
In mobile web development, there are multiple approaches to drawing a 0.5px line. Below are some common methods:
-
Using Viewport
Set the page's viewport to half the device width, and layout based on this new viewport width. When setting
border-width: 1px, it effectively renders as 0.5px in physical pixels.html<meta name="viewport" content="width=device-width,initial-scale=.5, maximum-scale=.5, user-scalable=no"> <div style="border-bottom: 1px solid #ccc"></div> -
Using CSS Transform Properties
This method is commonly applicable to most scenarios. The main idea is to add a 1px border and scale it using
scaleY(.5)/scaleX(.5). Note that when using this method to draw lines, scale using pseudo-elements to avoid affecting the container's layout.html<div class="line"></div>css.line { position: relative; height: 20px; } .line::after { content: ''; position: absolute; left: 0; bottom: 0; width: 100%; border-bottom: 1px solid #ccc; transform: scaleY(.5); } -
Using SVG
SVG is an XML-based vector graphics format, generated entirely by code, so it can achieve precision down to 0.5px. The implementation involves changing the
stroke-widthattribute in SVG.html<svg width="100%" height="1" version="1.1" xmlns="http://www.w3.org/2000/svg"> <line x1="0" y1="0" x2="375" y2="0" stroke="#000" stroke-width="0.5" /> </svg> -
Using Canvas
The Canvas API provides lower-level drawing capabilities, which can also achieve this requirement.
html<canvas id="canvas"></canvas> <script> var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(0, 0); ctx.lineTo(300, 0); ctx.lineWidth = 0.5; ctx.stroke(); </script>