I\'m looking for a reliable way to get the width of the window in em units using javascript. I was surprised to see that jQuery will only return a result in pixel measurements.
For those who need it all put together, this code works for me:
<p>Window size: <span id="width_px"></span> pixels or <span id="width_ems"></span> ems</p>
<script>
window.onresize = function() {
document.getElementById("width_px").innerHTML = window.innerWidth;
document.getElementById("width_ems").innerHTML = window.innerWidth / parseFloat($("body").css("font-size"));
};
</script>
It's put together using the answer above added to the window-width test code found in the linked tutorial.
Here's a solution that doesn't require jQuery, and doesn't require an explicit font-size declaration.
window.innerWidth / parseFloat(
getComputedStyle(
document.querySelector('body')
)['font-size']
)
Simple, since we know 1em = 16px
var window_width_em = 1/16 * window_width_px;
It's possible to calculate it, but em
isn't a "simple" unit like px
because it depends on a font selection (that is, a combination of typeface family, style (bold, italic, etc), and font size). Of course font size itself can be relative (e.g. if you give a font an em
, ex
, or percentage size then the computed px
height for that font is derived from the parent element's size).
To get the em
width of a page you could do the conversion like this (warning: psuedocode):
// For this to work reliably, size should be in px, pt, or mm.
function getWindowWidthInEm(fontFamily, style, size) {
var box = document.createElement("span");
box.innerText = "M";
box.style.fontFamily = fontFamily;
box.style.fontSize = size;
box.style.fontWeight = style is bold;
box.style.fontStyle = style is italic;
var body = document.getElementsByTagName("body")[0];
body.appendChild( box );
var emInPx = box.getComputedStyle().width;
body.removeChild( box );
var windowPx = window.width;
return windowx / emInPx;
}
This seems to work:
$(window).width() / parseFloat($("body").css("font-size"));