JSFiddle - React, Tailwind, and code Playground
HTML
<div id="log"></div>
<p class="test1">
first text block
<em>second text block</em>
</p>
<p class="test2">
first text block<br>
second text block
</p>
<p class="test3">
first text block
<em>second text block</em>
</p>
CSS
#log {
position: absolute;
right: 80px;
}
.rect {
border: 1px solid;
background-color: #b2ceea;
border-color: #76ade2;
position: absolute;
opacity: 0.5;
z-index: 100000;
}
.test1 {
width: 60px;
font-size: 14px;
line-height: 22px;
}
.test2 {
width: 180px;
font-size: 22px;
line-height: 32px;
}
.test3 {
width: 380px;
font-size: 54px;
line-height: 96px;
}
JavaScript
var highlight = function(rect) {
var div = document.createElement('div');
div.className = 'rect';
div.style.left = rect.left + 'px';
div.style.top = rect.top + 'px';
div.style.width = rect.width + 'px';
div.style.height = rect.height + 'px';
return document.body.appendChild(div);
};
var log = function(msg, msg2) {
document.getElementById('log').innerHTML += msg + ' ' + msg2 + '<br>';
};
var getRect = function(textNode) {
var range = document.createRange();
range.selectNode(textNode);
return range.getBoundingClientRect();
};
var getSpacing = function(textNode) {
var style = getComputedStyle(textNode.parentNode);
return parseInt(style.lineHeight, 10) - parseInt(style.fontSize, 10);
};
var test = function(textNode1, textNode2, num) {
var rect1 = getRect(textNode1),
rect2 = getRect(textNode2);
highlight(rect1);
highlight(rect2);
log('case-' + num + ', difference between rects: ', rect2.top - rect1.bottom);
log('case-' + num + ', spacing from line-height and font-size (node1): ', getSpacing(textNode1));
log('case-' + num + ', spacing from line-height and font-size (node2): ', getSpacing(textNode2));
};
var p = document.getElementsByTagName('p');
test(p[0].firstChild, p[0].firstChild.nextSibling.firstChild, 1);
test(p[1].firstChild, p[1].firstChild.nextSibling.nextSibling, 2);
test(p[2].firstChild, p[2].firstChild.nextSibling.firstChild, 3);