JSFiddle - React, Tailwind, and code Playground
by David Thomas
HTML
<div>
<div id="test">Some text</div>
</div>
CSS
body {
font-size: 3em;
}
div {
font-size: 12px;
}
div > div {
font-size: 16px;
}
JavaScript
var elem = document.getElementById('test');
function px2em(elem) {
var W = window,
D = document;
if (!elem || elem.parentNode.tagName.toLowerCase() == 'body') {
return false;
}
else {
var parentFontSize = parseInt(W.getComputedStyle(elem.parentNode, null).fontSize, 10),
elemFontSize = parseInt(W.getComputedStyle(elem, null).fontSize, 10);
var pxInEms = Math.floor((elemFontSize / parentFontSize) * 100) / 100;
elem.style.fontSize = pxInEms + 'em';
}
}
px2em(elem);