Search code examples
htmlcssdevicepixelratio

How to make a ruler to measure "cm"?


As far as I knew, the CSS unit "CM" is only for print media types.
What if I want to make a ruler that can precisely measure "CM"?

I found using 1cm in stylesheet can be rendered correctly under certain circumstances like the screen is with devicePixelRatio = 1 (on a 1920 x 1080 extended screen) and 50px is pretty close to 1cm on the screens with devicePixelRatio = 2(on a Macbook Air M1 Retina Screen)

A very rough example is like the following: https://codesandbox.io/p/sandbox/unit-cm-x7vvsy?file=/src/App.js

I wondered if there's a solid equation to render exact length as "cm" on screens?


Solution

  • Unfortunately, screens in general are not designed to represent these units accurately. Citing the W3C documentation

    The relation between the absolute units is as follows: 1in = 2.54cm = 25.4mm = 72pt = 6pc

    [sample schema]

    The so-called absolute units (cm, mm, in, pt and pc) mean the same in CSS as everywhere else, but only if your output device has a high enough resolution. On a laser printer, 1cm should be exactly 1 centimeter. But on low-resolution devices, such as computer screens, CSS doesn't require that.

    If this is a requirement, you could design some kind of calibration procedure, asking your user to adjust a scale parameter until a 10cm ruler is represented accurately enough.