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.
innerHeight() - Returns the height of an element (includes padding) outerWidth() - Returns the width of an element (includes padding and border) outerHeight() - Returns the height of an element (includes padding and border)
Method 1: Using the offsetHeight property: The offsetHeight property of an element is a read-only property and used to return the height of an element in pixels. It includes any borders or padding of the element. This property can be used to find the height of the <div> element.
offsetHeight read-only property returns the height of an element, including vertical padding and borders, as an integer. Typically, offsetHeight is a measurement in pixels of the element's CSS height, including any borders, padding, and horizontal scrollbars (if rendered).
Answer: Use the JavaScript height() method You can set the height of a <div> box dynamically using the jQuery height() method.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With