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.
3 Answers
1px = 0.02645833 cm;
or
1 cm = 37.795276px;
See these links:
How to access screen display’s DPI settings via javascript?
- 1
- 1
- 84,459
- 21
- 136
- 161
-
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
-
2Is 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
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
- 2,481
- 1
- 19
- 17
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.
- 128,537
- 12
- 134
- 188
-
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
-
-
Hazard warning: "First you need to decide how many DPI (Dots Per Inch) you are looking at." – Tim Ogilvy Jun 27 '17 at 01:10