Consider the following code (an inline <span> contained within a block-level <div>):
<div>
<span style="font-size:40px;line-height:3px;">HELLO</span>
</div>
This will result in the <div> having a height of 19px. How did the browser arrive at this value of 19px?
The following snippet is that code in action:
<!doctype html>
<html lang="en" style="font-family:'Arial';">
<head>
<meta charset="utf-8"/>
<title>Line-Height Test</title>
</head>
<body style="padding-top:50px;padding-right:calc(100% - 300px);">
<div id="greenDiv" style="background-color:lightgreen;">
<span style="font-size:40px;line-height:3px;">HELLO</span>
</div>
<div id="infoDiv" style="margin-top:20px;"></div>
<script>
(() => {
const infoDiv = document.getElementById("infoDiv");
const greenDiv = document.getElementById("greenDiv");
let html = `The inner <span> is ${greenDiv.firstElementChild.offsetHeight}px tall,`;
html += ` but its container (the outer green <div>) is only ${greenDiv.offsetHeight}px tall.`;
html += `<br/>How did the browser arrive at this ${greenDiv.offsetHeight}px value?`;
infoDiv.innerHTML = html;
})();
</script>
</body>
</html>
To better understand, make the
line-heightequal to0and you will get a height equal to18pxfor the div. The div has the defaultfont-sizeequal to16pxand the defaultline-heightis equal tonormal. Thenormalvalue is based on the font and in this case it seems to be equal to1.125to have18px = 1.125 * 16pxNow, if you start increasing the
line-heightof the span, the height of the div will increase due to the vertical alignment. This is a bit tricky because we need some complex calculation to identify the final height but if you change the alignment of the span to something different frombaseline(the default one), the height will get back to18pxwhataver theline-heightI am using
line-height: 18pxwith a top alignment and the total height is still18px. If I increase theline-heightof the span, the height will also increase. If you update the alignment the height will also increase.To conclude, the
line-heightandfont-sizeof the div will set a minimum height. This minimum height can be changed by theline-heightof the inner element and their vertical alignment.Related questions:
How does height will be calculated, based on font-size?
Why inline and inline-block have different height with the same text content
How to determine height of content-box of a block and inline element