【问题标题】:height vs line-height styling高度与行高样式
【发布时间】:2011-09-30 22:14:55
【问题描述】:

在处理永远不会超过一行的文本时,使用这两者有什么区别?从我所看到的关于元素顶部或底部的元素,它们都可以在屏幕上产生类似的结果。如果是这样,为什么要使用 line-height 呢?使用高度会更有意义。

编辑:一个从带有文本的 div 创建的风格化按钮的示例。这永远不会是多行的。那么出于兼容性原因需要行高吗?或任何我不知道的事情?

谢谢!

【问题讨论】:

    标签: html css styling


    【解决方案1】:

    height是容器的垂直尺寸。

    line-height是第一行文本顶部到顶部的距离 第二个。

    如果仅与一行文本一起使用,我希望它们在大多数情况下会产生类似的结果。

    当我想显式设置容器大小时,我使用height,而在排版布局中使用line-height,如果用户调整文本大小,这可能是相关的。

    【讨论】:

    • 更正。 line-height 与第二行文本的位置无关,仅基于行内框本身。
    • 这是另一个来自css-tricks 的示例教程,如果这更有意义的话。
    【解决方案2】:

    如果你将文本包裹在一个 div 中,给 div 一个高度,文本增长到 2 行(可能是因为它正在像手机这样的小屏幕上查看),那么文本将与下面的元素重叠它。另一方面,如果你给 div 一个 line-height 并且文本增长到 2 行,那么 div 将会扩展(假设你没有给 div 一个高度)。

    这是一个证明这一点的fiddle

    【讨论】:

    • 在阅读this 后登陆 SO。 DwB 的回答应该得到更多的支持。
    【解决方案3】:

    假设文本小于容器:

    在容器上设置 line-height 可以指定其中 line-boxes 的最小高度。对于 1 行文本,这会导致文本在容器内垂直居中。

    如果您在容器上设置高度,则容器将垂直增长,但其中的文本将从其内部的第一(顶)行开始。

    【讨论】:

      【解决方案4】:

      高度 = 行高 + padding-top + padding-bottom

      【讨论】:

        【解决方案5】:

        出于实际目的,在您引用的情况下(从不换行超过一行) line-height 将使文本垂直居中。尽管用户最终控制字体大小,但请注意该假设。

        【讨论】:

          【解决方案6】:

          看这个例子就容易理解了。

          .height
          {
              height: 20px;
          }
          
          .lheight
          {
              line-height: 15px;
          }
          
          .lheightbigger
          {
              line-height: 35px;
          }
          <h2>Height</h2>
          <div class="height">
            This is demo text. This is demo text.
            This is demo text. This is demo text. 
            This is demo text. This is demo text.
          </div><br>
          <h2>Line Height with less space</h2>
          <div class="lheight">
            This is demo text showing line height example. This is demo text showing line height example.
            This is demo text showing line height example. This is demo text showing line height example.
            This is demo text showing line height example.This is demo text showing line height example.
          </div>
          <h2>Normal Text</h2>
          <div>
            This is normal text.
            This is normal text.
            This is normal text.
          </div>
          <h2>Line Height with more space</h2>
          <div class="lheightbigger">
            This is normal text. This is normal text.This is normal text.
            This is normal text. This is normal text.This is normal text.
            This is normal text. This is normal text.This is normal text.
          </div>

          【讨论】:

            猜你喜欢
            • 2012-11-10
            • 1970-01-01
            • 2018-09-14
            • 2011-11-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多