我的问题是哪种行为是正确的。
所有这些都是正确的,因为我们在所有浏览器中没有相同的默认字体,并且它也因操作系统而异。
是否允许特定字符更改行高(我认为它应该只取决于字体)?
字符不会改变line-height。更准确地说,line-height 是一个只能通过设置 line-height 来更改的属性,但您可能对line-height 定义的行框感到困惑,并且单独一个字符无法更改它。
不应该 line-height: 1 暗示它可以完全适合任何文本吗?
不一定,line-height:1 表示行框将等于1xfont-size 1 但字体是否设计为包含此空间内的所有字符?可能他们中的大多数人都会这样做,但我们不知道。
基本上,您需要考虑两件事。由字体属性定义的内容区域和由行高定义的行框。我们无法控制第一个,只能控制第二个。
下面是一个基本的例子来说明:
span {
background:red;
color:#fff;
font-size:20px;
font-family:monospace;
}
body {
margin:10px 0;
border-top:1px solid;
border-bottom:1px solid;
animation:change 2s linear infinite alternate;
}
@keyframes change {
from {
line-height:0.2
}
to {
line-height:2
}
}
<span >
blah_blah
</span>
红色是我们的内容区域,它的高度由字体属性定义,如果您检查元素,您会看到它的高度等于23px(不是20px,如font-size)和边框定义我们使用 line-height 控制的线框。
所以如果line-height 等于1,我们将有一个等于20px 的行框,它不足以包含内容区域的23px,因此它将被截断,我们可能会隐藏一些字符(或其中的一部分)这是合乎逻辑的:
span {
background: red;
color: #fff;
font-size: 20px;
font-family: monospace;
}
body {
margin: 5px;
line-height: 1;
overflow:hidden;
}
html {
overflow:auto;
}
<span>
blah_blah ÂÄ j p
</span>
不同的font-size 将删除 Firefox 中的下划线:
span {
background: red;
color: #fff;
font-size: 26px;
font-family: monospace;
}
body {
margin: 5px;
line-height: 1;
overflow:hidden;
}
html {
overflow:auto;
}
<span>
blah_blah ÂÄ j p
</span>
另一个使用谷歌字体的例子,结果应该是相同的跨浏览器。下划线可见但^/¨不可见
span {
background: red;
color: #fff;
font-size: 26px;
font-family: 'Gugi', cursive;
}
body {
margin: 5px;
line-height: 1;
overflow:hidden;
}
html {
overflow:auto;
}
<link href="https://fonts.googleapis.com/css?family=Gugi" rel="stylesheet">
<span>
blah_blah ÂÄ j p
</span>
下划线不可见的另一个例子:
span {
background: red;
color: #fff;
font-size: 27px;
font-family: 'PT Sans', sans-serif;
}
body {
margin: 5px;
line-height: 1;
overflow:hidden;
}
html {
overflow:auto;
}
<link href="https://fonts.googleapis.com/css?family=PT+Sans" rel="stylesheet">
<span>
blah_blah ÂÄ j p
</span>
您可以清楚地看到,每次我们使用不同的字体时都会出现不同的溢出,这证实了这是与字体相关的。除非我们知道字体是如何设计的,否则我们无法控制它。
相关问题:
Understanding CSS2.1 specification regarding height on inline-level boxes
Why is there space between line boxes, not due to half leading?
Line height issue with inline-block elements
这里有一篇好文章可以获得更准确的细节和计算:https://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align
引用这篇文章:
很明显,设置line-height: 1 是一种不好的做法。我提醒您,无单位值是相对于字体大小的,而不是相对于内容区域的,处理小于内容区域的虚拟区域是我们许多问题的根源。
1 : 我考虑了一个简化的解释,但实际上线框的计算不仅与 line-height 属性有关。