getting height of a div in centimeter using jquery?

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.

Answers:

Answer

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

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.