当您编写此代码时:(在Chrome中)
<div style="font-size: 32px">txt</div>Run Code Online (Sandbox Code Playgroud)
其高度将为37px。但是这个:
<div style="font-size: 16px">txt</div>Run Code Online (Sandbox Code Playgroud)
其高度将为18px。
所以我的问题是:是否有任何公式可以计算渲染时文本的高度(基于字体大小)?
高度不是基于,font-size而是line-height默认值是normal
取决于用户代理。桌面浏览器(包括Firefox)使用的默认值约为1.2,具体取决于元素的字体系列。参考
基本上,我们line-height不确切知道的值,但是如果我们明确定义它的值,则可以知道确切的高度。
我将高度设置为 1.5 x font-size
$('div').each(function(){
console.log($(this).height());
})Run Code Online (Sandbox Code Playgroud)
div {
line-height:1.5;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="font-size: 32px">txt</div>
<div style="font-size: 16px">txt</div>Run Code Online (Sandbox Code Playgroud)
高度35px适合所有人的另一个:
$('div').each(function(){
console.log($(this).height());
})Run Code Online (Sandbox Code Playgroud)
div {
line-height:35px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="font-size: 32px">txt</div>
<div style="font-size: 16px">txt</div>Run Code Online (Sandbox Code Playgroud)
值得注意的是,如果考虑内联元素,结果将有所不同:
$('div').each(function(){
console.log("div "+$(this).height());
})
$('span').each(function(){
console.log("span "+$(this).height());
})Run Code Online (Sandbox Code Playgroud)
div,span {
line-height:1.5;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="font-size: 32px">txt</div>
<div style="font-size: 16px">txt</div>
<span style="font-size: 32px">txt</span>
<span style="font-size: 16px">txt</span>Run Code Online (Sandbox Code Playgroud)
或者,如果您font-size在div内有不同的内容或不同的对齐方式:
$('div').each(function() {
console.log("div " + $(this).height());
})Run Code Online (Sandbox Code Playgroud)
div {
line-height: 1.5;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span style="font-size: 32px">txt</span>
<span style="font-size: 16px">txt</span>
</div>
<div>
<span style="font-size: 32px;vertical-align:text-top">txt</span>
<span style="font-size: 32px">txt</span>
</div>Run Code Online (Sandbox Code Playgroud)
在第一种情况下,高度将仅根据字体属性定义(line-height在此不起作用)。
内容区域的高度应基于字体ref
在未替换的内联元素上,“ line-height”指定用于计算线框高度的高度。
在第二种情况下,我们有一个更现实的示例,其中高度不仅基于,line-height而且考虑不同元素的对齐以找到我们需要的最终高度,以放置所有元素。
此处有更多详细信息:https : //www.w3.org/TR/CSS2/visudet.html#line-height
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |