13

I'm having a div , in which I am adding data dynamically, I want to get the height of the particular div in centimeter. Because I need to control the amount of data that can be displayed in that div based on the height.

TRR
  • 1,637
  • 2
  • 26
  • 43
Rosh
  • 1,676
  • 4
  • 21
  • 35

3 Answers3

18
1px = 0.02645833 cm;

or

1 cm = 37.795276px;

See these links:

How to access screen display’s DPI settings via javascript?

How to detect the screen DPI using JavaScript

Pixel to Centimeter?

Community
  • 1
  • 1
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • This was what was missing from my answer.... how to determine the screen DPI using JS. Well done +1 – Jamiec May 29 '12 at 08:01
  • 2
    Is it the same in all screens? I doubt if 1 cm consists of same amount of pixels in different screens. – Sassan Mar 08 '17 at 10:04
13

Here is a little javascript function to convert CSS pixels to centimeters:

function px2cm(px) {
  var d = $("<div/>").css({ position: 'absolute', top : '-1000cm', left : '-1000cm', height : '1000cm', width : '1000cm' }).appendTo('body');
  var px_per_cm = d.height() / 1000;
  d.remove();
  return px / px_per_cm;
}

It inserts a 1000cm x 1000cm empty <div> into the page and then read its height in CSS pixels. By not using magic values (as 1px = 0.02645833 cm suggested above, which only work if your screen DPI is 96) it ensures that the current screen DPI is taken into account.

As the DPI of a screen can never change, you should cache the px_per_cm to avoid any performance hit any time you call this function

Jonathan Pasquier
  • 2,561
  • 1
  • 19
  • 17
6

First you need to decide how many DPI (Dots Per Inch) you are looking at. On a screen this is usually between 72 and 100. Lets take 72 as an example.

72 Dots (Pixels) per Inch.
Which is 72 Pixels per 2.54cm
So 1 cm is 28.35pixels

Now just get the height in pixels, and do the conversion.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • i'm getting 140 dpi ,I'm not getting the above calculation of 72px per 2.54cm, how much cm will it come for 140 and how?.. thanks in advance – Rosh May 29 '12 at 08:56
  • @user976034 `72 / 2.54 = 28.35` - does this help you do your calculation if your screen is 140 DPI? – Jamiec May 29 '12 at 09:49
  • thanks jamiec, my doubt was whether 2.54 is fixed or its depend upon dpi..any way its cleared – Rosh May 29 '12 at 10:20
  • @user976034 - 2.54 is the number of cm in 1 inch. – Jamiec May 29 '12 at 10:21
  • Hazard warning: "First you need to decide how many DPI (Dots Per Inch) you are looking at." <-- or maybe your user, which is far more important. Too many people still make the assumption "my screen is the only screen in the universe". See the accepted answer for how to detect this. – Tim Ogilvy Jun 27 '17 at 01:10