Minimalist Semantic Markup

Welcome Guest
Please Login or Register

If you have registered but not recieved your activation e-mail in a reasonable amount of time, please use our Contact Form for assistance. Include both your username and the e-mail you tried to register with.

Author Topic: JavaScript: Showing the width/height in EM  (Read 103 times)

Jason Knight

  • Administrator
  • Sr. Member
  • *****
  • Posts: 405
  • Karma: +62/-1
    • CutCodeDown -- Minimalist Semantic Markup
JavaScript: Showing the width/height in EM
« on: 11 May 2020, 08:16:41 am »
Whilst a lot of browsers have extensions that will tell you the dimensions of the client area, it's sometimes nice to just be able to temporarily include a script to have it shown.

Code: [Select]
(function(d, w) {

dispX = d.body.appendChild(d.createElement('div')),

dispX.setAttribute('style', '\
font:normal 1rem/1.5em arial,helvetica,sans-serif;\
padding:0.25em 0.5em;\

function dispXUpdate() {
dispX.textContent = 'Dim: ' +
(w.innerWidth / emSize) +
'em x ' +
(w.innerHeight / emSize) +

w.addEventListener('load', function() {
emSize = dispX.clientHeight / 2; // 0.25em top/bottom padding + 1.5em line-height == 2em
w.addEventListener('resize', dispXUpdate, false);
}, false);

})(document, window);

What's nice about this is it tells you the value in BODY REM, which is what EM for your media queries should be, making it easier when resizing to determine your breakpoints. Just include this script right before </body> in your code when you want to take your responsive layout measurements.

I've used this script for years, and it's part of my normal workflow.

Also one of the few times I'd ever advocate setting style from the script, since this is a temporary tool not part of the page's normal codebase.
Sorrow hides well in your shell. A fellow man with hurt to spare.
Dear one, here I am to share the fear. An act of kindness, without an amen.
Come in, the fire's warm. Burn the rope and dance some more.