DEV Community

Narongdej Sarnsuwan
Narongdej Sarnsuwan

Posted on • Originally published at narongdej.dev on

Real-world inch in CSS

In web development, a CSS inch is not the same across all devices. That’s because every screen has a different PPI or Pixel Per Inch.

1 inch in CSS equal 96px. That 1 inch will only be equal to 1 real-world inch that you can find in your typical ruler if your screen is exactly 96 dpi. For example, a 23” monitor with 1920 x 1080 resolution will have about 96 PPI while an iPhone 11 Pro Max with a much smaller screen, but with much higher resolution will have 456 PPI. If you draw a 1 CSS inch line or 96px, it will much shorter on the iPhone than on the 23 inch monitor.

So can you make your web display the 1 CSS inch line as a real-life inch across all devices? The answer is you can, kinda. Cause you’ll need to know the screen PPI, and the browser cannot give you the monitor PPI.

However, you can predict the PPI using the User Agent (ex. iPhone 11 Pro Max) or, just straight ask the user. To calculate the PPI, you’ll need the screen diagonal in inch and diagonal in pixel. Then divide the diagonal in pixel with diagonal an inch to get the PPI. (or just use dpi.lv)

After that, you’ll be able to adjust the line size accordingly.

var node = document.querySelector('#line')
node.style.width = (node.clientWidth / 96.0) * (<<the_screen_dpi>> / window.devicePixelRatio)

Enter fullscreen mode Exit fullscreen mode

Lastly, the window.devicePixelRatio returns the size of one CSS pixel to the size of one physical pixel. For example, for the retina display, this number will be 2.

Top comments (0)