Device Pixel Ratio & Subpixel Rendering
A CSS px is an angular unit, not a hardware dot. window.devicePixelRatio (DPR) maps CSS pixels to physical screen pixels; fractional coordinates or unscaled <canvas> buffers force bilinear filtering, blurring edges and text.
CSS Pixel to Physical Pixel Mapping
Adjust devicePixelRatio and fractional CSS coordinates to see physical pixel alignment.
Under the Hood
CSS coordinates are a floating-point blueprint, whereas your monitor is a rigid grid of physical LEDs. When a line lands halfway between two LEDs, the rasterizer smears it across both.
- Subpixel Layout: Render Tree & Layout stores box edges in fixed-point fractions (e.g.,
1/64px). - Border Snapping: During Paint & Rasterization, engines snap borders and backgrounds to whole device pixels so
1pxlines stay crisp. - Canvas & Transforms:
<canvas>backing stores andtransform: translate()bypass layout snapping unless explicitly scaled bydevicePixelRatio.
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = Math.round(rect.width * dpr);
canvas.height = Math.round(rect.height * dpr);
ctx.scale(dpr, dpr);Problem Genealogy
- 2010 (HiDPI / Retina): Apple doubled physical pixel density (
dpr = 2) while keeping CSSpxinvariant, exposing unscaled bitmaps and<canvas>buffers. - 2016+: Fractional DPR (
1.25,1.5,2.625) became common on Windows and Android, making naiveMath.floor(dpr)rounding produce uneven borders.
Production Pitfalls
- Blurry
<canvas>on HiDPI: Setting only CSSwidthandheightstretches a 1x bitmap across 2x or 3x physical pixels. translate(-50%, -50%)on odd-sized boxes: Centering an odd-height modal with-50%places text on a half-pixel boundary, softening glyph edges.
- When not to use
0.5pxborders: Avoidborder: 0.5px solidfor hairlines on low-DPR screens where it rounds to0pxor1px; use1pxortransform: scaleY(0.5)gated bymin-resolution: 2dppx.
Connections & Logical Next Steps
Compositor layer textures rasterize at devicePixelRatio scale and snap subpixel transforms to physical pixels.
Device pixel ratio and subpixel anti-aliasing alter edge pixel luminance across host GPUs.
Rasterization maps floating-point CSS layout coordinates onto discrete physical device pixels.
Layout computes fractional CSS pixels before Paint snaps borders and transforms.