offsetHeight溢出时与父元素高度相等,如何正确获取高度适配字体?
问题描述
我想设置字体大小以适配div容器的尺寸。之前在类似场景见过用offsetWidth的案例,因为我是垂直方向溢出,所以选了offsetHeight。但发现带文本的div的offsetHeight和父div的offsetHeight数值一样。试了element.parentElement.parentElement.offsetHeight,但祖父元素包含footer组件,导致溢出计算不准。想问是不是用错了属性,或者获取高度的方式不对?
代码示例
JavaScript
for (const element of document.getElementsByClassName("shrink")) { var size = 32; console.log(element.offsetHeight, element.parentElement.offsetHeight, element.parentElement.parentElement.offsetHeight) while (element.offsetHeight > element.parentElement.offsetHeight) { element.style.fontSize = size + "pt" size -= 1 } }
CSS
.party_card { padding: 1em 1em; display: flex; flex-direction: column; justify-content: space-between; height: 100%; width: 100%; border: 1px black solid; } .party_cardtext { display: block; text-align: left; font-size: 32pt; word-break: break-word; flex-grow: 1; } #container { display: flex; height: 200px; } .footer { min-width: 0; display: flex; flex-direction: row; justify-content: space-between; margin-top: 0.5em; }
HTML
<div id="container"> <div class="party_card"> <div class="party_cardtext"> <div class="shrink">Short text</div> </div> <div class="footer"> <span>foo</span> <span>bar</span> </div> </div> <div class="party_card"> <div class="party_cardtext"> <div class="shrink">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div> </div> <div class="footer"> <span>foo</span> <span>bar</span> </div> </div> </div>
解决方案
问题根源
你的shrink元素的父元素.party_cardtext设置了flex-grow: 1,它会自动填充.party_card里footer之外的剩余空间,所以shrink的offsetHeight会被父元素撑开,和父元素高度一致,导致循环条件永远不触发。同时offsetHeight只能获取元素的可视高度,无法判断内容是否溢出。
修复方案
- 用
scrollHeight判断溢出:scrollHeight是元素内容的总高度(包括溢出部分),对比容器的clientHeight(可视高度),能准确判断文本是否超出容器。 - 直接使用父容器的可用高度:
.party_cardtext的clientHeight就是footer之外的可用空间,直接用这个数值作为判断基准即可。
修改后的代码
JavaScript
for (const element of document.getElementsByClassName("shrink")) { const cardTextContainer = element.parentElement; let fontSize = 32; // 先设置初始字号 element.style.fontSize = `${fontSize}pt`; // 循环缩小字号,直到内容不溢出或达到最小限制 while (element.scrollHeight > cardTextContainer.clientHeight && fontSize > 8) { fontSize -= 1; element.style.fontSize = `${fontSize}pt`; } }
CSS(新增溢出隐藏)
.party_cardtext { display: block; text-align: left; font-size: 32pt; word-break: break-word; flex-grow: 1; overflow: hidden; /* 隐藏溢出内容 */ } /* 其余样式保持不变 */
关键说明
scrollHeightvsoffsetHeight:offsetHeight仅返回元素自身的可视高度,scrollHeight会包含溢出的内容高度,是判断垂直溢出的更准确属性。- 最小字号限制:给循环加最小字号(如8pt),避免字体无限缩小影响可读性。
内容的提问来源于stack exchange,提问作者marmistrz
相关产品推荐
相关产品推荐

