子元素font-size越小父元素height越大?求解析及非flex解决方案
原因分析
这个现象是行内元素排版规则和字体自身特性共同导致的:
行内元素默认以baseline(基线)垂直对齐,而每种字体都有固定的基线位置、字符顶部到基线的上升高度(ascent)、基线到字符底部的下降高度(descent)。当子元素的font-size远小于父元素设置的line-height时,浏览器会基于字体的ascent/descent比例来分配行框(line box)的上下空间,以保证字体排版的完整性,最终导致行框高度超过设定的20px——font-size越小,这种比例失衡越明显,行框被撑开的幅度就越大。
而设置display:flex后,flex容器的交叉轴布局逻辑会忽略行内元素的基线对齐规则,默认让子元素在交叉轴上居中,容器高度直接由子元素的line-height(20px)决定,因此能保持设定值。
非Flex解决方案
以下几种方法可以让父元素高度固定为20px,无需使用flex布局:
1. 修改子元素垂直对齐方式
给子元素设置vertical-align: top/middle/bottom,改变默认的基线对齐逻辑,让行框高度严格遵循设置的line-height:
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .city-parent { line-height: 20px; } .city { font-size: 6px; line-height: 20px; vertical-align: top; } </style> </head> <body> <div class="city-parent"> <span class="city">City of a country with a quite long name</span> </div> </body> </html>
2. 重置父元素字体大小
给父元素设置font-size: 0,消除父元素自身字体对行框高度的影响,行框高度完全由子元素的line-height控制:
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .city-parent { line-height: 20px; font-size: 0; } .city { font-size: 6px; line-height: 20px; } </style> </head> <body> <div class="city-parent"> <span class="city">City of a country with a quite long name</span> </div> </body> </html>
3. 强制父元素高度
直接给父元素设置height: 20px,配合overflow: hidden(触发块级格式化上下文)强制容器高度固定:
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .city-parent { line-height: 20px; height: 20px; overflow: hidden; } .city { font-size: 6px; line-height: 20px; } </style> </head> <body> <div class="city-parent"> <span class="city">City of a country with a quite long name</span> </div> </body> </html>
内容的提问来源于stack exchange,提问作者Pipo
相关产品推荐
相关产品推荐

