【问题标题】:How CSS line-height is measured?CSS line-height是如何测量的?
【发布时间】:2014-04-23 23:12:04
【问题描述】:

CSS 中的 line-height 是从文本底部到下一行文本的底部吗?还是文本在行内垂直居中?

请看示例图片:

【问题讨论】:

  • 来自 W3 文档:On a block container element whose content is composed of inline-level elements, 'line-height' specifies the minimal height of line boxes within the element. The minimum height consists of a minimum height above the baseline and a minimum depth below it, exactly as if each line box starts with a zero-width inline box with the element's font and line height properties. We call that imaginary box a "strut." (The name is inspired by TeX.).
  • 第一个例子是line-height 的行为
  • 左图是正确的 ;)
  • 您经常会看到人们使用 Line-Height 来垂直对齐 div 内的单行文本,方法是将 line-height 设置为与 div 相同的高度。
  • 今后,请不要交叉发布问题。找到最合适的网站并坚持使用该网站。我将在此处合并您的两个问题以合并答案。

标签: css


【解决方案1】:

Form MDN

在块级元素上,行高 CSS 属性指定 元素内线框的最小高度。

在不可替换的内联元素上,line-height 指定的高度 用于计算行框高度。


正如您在此 DEMO 和以下图片中看到的那样。这意味着对于文本,line-height 定义了围绕在该框内垂直居中的字母的框的高度,因此您的第一个示例是正确的

图片来自www.w3.org

【讨论】:

    【解决方案2】:

    正如我已经评论过的,第一个示例是 line-height 的实际行为。

    根据我image is wrong 的说法,图像中的line-height 是从基线到基线计算的,而line-height 是在垂直两侧计算的,它是通过将数字乘以元素font-size 来计算的。

    例如,我创建了一个示例

    div {
        outline: 1px solid #f00;
        line-height: 40px;
    }
    

    Demo

    在上面的例子中,line-height 的作用类似于padding-toppadding-bottom 属性(它并不是真正的填充),这就是它的真正工作原理。

    【讨论】:

    • 如果我错了,请纠正我,但只要line-height 定义了文本行框的高度并且所有框的文本以相同的方式在其框内垂直对齐,这意味着line-height 是基线之间的空间。
    • From the spec: 注意。 当块容器框中的所有内联框只有一个 line-height 值并且它们是全部使用相同的字体(并且没有替换元素、行内块元素等),以上将确保连续行的基线完全分开line-height
    【解决方案3】:

    找到这张图片,所以这是你的第一个例子,line-height

    【讨论】:

    • 在您的图像中,它显示了从第一行字母底部到第二行字母底部的行高,因此它看起来更像 OP 图像中的第二个示例
    • @web-tiki 第二个例子是 baseline
    • 该死的,我现在糊涂了!我必须再看一遍OP的照片。
    • 是的,图片令人困惑
    • @Mr.Alien - 我认为 web-tiki 可能是对的,从基线到基线是 line-height ?
    【解决方案4】:

    对我来说,这似乎是图片中显示的第一个示例。我们来看看这段代码:

    CSS

    div {
        width:120px;
        height:30px;
        border:1px solid black;
        margin-bottom:5px;
    }
    #box2 {
        line-height:30px;
    }
    #box3 {
        line-height:10px;
    }
    #box4 {
        line-height:60px;
    }
    

    HTML

    <div id="box1">No line-height</div>
    <div id="box2">30px line-height</div>
    <div id="box3">10px line-height</div>
    <div id="box4">60px line-height</div>
    

    在这里拉小提琴:

    http://jsfiddle.net/58CJw/

    看起来 line-height 确实是fontSize + spaceAbove + spaceBelow,其中spaceAbove = spaceBelow

    【讨论】:

      【解决方案5】:

      线条垂直居中。这就是为什么您可以使用line-height 将一行元素垂直居中。

      【讨论】:

        【解决方案6】:

        line-height property 粗略的指定了 line box 的最小高度;确切的效果取决于上下文(参见规范)。

        从图像中无法判断真正的问题是什么。

        【讨论】:

        猜你喜欢
        • 2020-05-23
        • 2021-07-14
        • 1970-01-01
        • 1970-01-01
        • 2013-05-11
        • 1970-01-01
        • 2010-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多