I am confusing about css units a lot. I just want to know one thing:
If I want my text's font-size is exact 4mm physically in any devices and any cases.
How can I do it?
While there is the mm
unit in CSS, it does not necessarily reflect the real physical size when being shown on a screen. There is no way to ensure exact physical dimensions on all devices and all cases.
CSS units for screen media are anchored to the px
unit which is not based on physical pixels but on the reference pixel.
The reference pixel is the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm’s length. For a nominal arm’s length of 28 inches, the visual angle is therefore about 0.0213 degrees. For reading at arm’s length, 1px thus corresponds to about 0.26 mm (1/96 inch).
The reference pixel thus highly depends on the device you are using and it may or may not result in correct physical dimensions.
Since CSS supports mm
as a unit, you could use font-size: 4mm;
. This, however, should only get used for printing stylesheets (cf. https://www.w3.org/Style/Examples/007/units.en.html), so you really try to avoid those units and just use units like px
or em
for other purposes.
If, however, you really (!) need to use those units, you could also use those units (but I would strongly advise against that).
Below is the example code:
<div id='testdiv' style='height: 1in; left: -100%; position: absolute; top: -100%; width: 1in;'></div>
<script type='text/javascript'>
var devicePixelRatio = window.devicePixelRatio || 1;
dpi_x = document.getElementById('testdiv').offsetWidth * devicePixelRatio;
dpi_y = document.getElementById('testdiv').offsetHeight * devicePixelRatio;
function setFontSizeForClass(className, fontSize) {
var elms = document.getElementsByClassName(className);
for(var i=0; i<elms.length; i++) {
elms[i].style.fontSize = String(fontSize * dpi_y / 96) + "px";
}
}
setFontSizeForClass('h1-font-size', 30);
setFontSizeForClass('action-font-size', 20);
setFontSizeForClass('guideline-font-size', 25);
</script>
More details on what it does and how to use it: https://stackoverflow.com/a/54190669/1915854