html - 使用 rem-value 中的字体计算行高

标签 html css

我怎样才能计算出最适合用 rem 设置的字体大小的行高?

例如:

html {
    font-size: 62.5%;
}

p {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
    font-size: 1.4rem;
    line-height: 1.3; /* how do i calculate this value? */
}

我问这个问题的原因是我很困惑如何理解 body 中的字体大小(为了便于 rem 计算)、实际 rem 字体大小和行高中的“非值”之间的关系据我所知,在 STATIC 布局中表示字体大小如下:

font-size: 20px;line-height: 2.0; - 会将 font-size 的高度添加为 line-height

在流畅的布局中——当在 font-size 中使用 rem 时——“非值”line-height: 2.0;使用以 rem 计算的字体高度作为行高,还是仍然依赖基于像素的值(在示例中是旧浏览器的回退)?
我想我应该把这是我原来的问题 - 我现在就编辑

最佳答案

嗯,在我看来,所有这些 ( <number> | <length> em | <percentage> ) 相关措施可能适用于 line-height 属性(property)。

<number> The used value is this unitless <number> multiplied by the element's font size. The computed value is the same as the specified <number>. In most cases this is the preferred way to set line-height with no unexpected results in case of inheritance.

<length> The specified <length> is used in the calculation of the line box height.

<percentage> Relative to the font size of the element itself. The computed value is this percentage multiplied by the element's computed font size. Percentage and em values may have unexpected results.

number之间的区别和 percentageem :

根据 MDN doc ,这个无单位的数字乘以元素自身的font-size (也适用于当前元素的每个子元素)。

在使用 percentage 时或 em对于父元素,使子元素服从其父元素的计算 line-height .

检查 this demo 以查看实际中的问题。

综合考虑

在这种情况下,所有这些值都具有相同的效果:

p {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
  font-size: 1.4rem;

  line-height: 1.3;   /*  = 1.3 * computed font-size */
  line-height: 130%;  /*  = 1.3 * computed font-size */
  line-height: 1.3em; /*  = 1.3 * computed font-size */
}

但是如果你想计算rem中的行高值单位,您可以使用以下内容:

html {
  font-size: 62.5%; /* ~10px = 16px(default) * 0.625 */
}

p {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 14px;
  font-size: 1.4rem;
  line-height: 1.3; /* as fallback */
  
  /* value = (10px * 1.4 * 1.3) / 10px = 1.82rem
               |      |     |
      <html>   |      |     --> line-height multiplier (same as <number>)
   font-size <--      |
       in px          --> Current element's font-size ratio
  */
  line-height: 1.82rem;
}

span { background-color: gold; } /* for demo */
<p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit.
  Consectetur quis omnis repellat voluptates necessitatibus repellendus
  sapiente nesciunt vero dolorem voluptate mollitia ex a quo consequuntur
  quia quasi aperiam quibusdam maiores.</span></p>

仅供引用: 默认值为 font-size<html>16px在大多数网络浏览器中,但是它不会对我们的计算进行任何更改。

JSBin Demo .

关于html - 使用 rem-value 中的字体计算行高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21379236/

相关文章:

html - Bootstrap 日期选择器样式被 CSS 表格样式覆盖

html - css 中的不透明度值

javascript - child 的 z-index 被 parent 覆盖

css - 根据 React 中的页面更改导航栏背景颜色

html - 什么时候在 CSS 中使用前缀 -moz、-webkit、-o 而不是简单的属性?

html - 更改 CSS 菜单上的字体大小

android - html视频不在android webview中播放

jquery - 如何使用 jquery 根据另一个下拉列表的选择来更改下拉列表值

javascript - jQuery用一个元素替换多个元素

html - 具有方形单元格和居中内容的固定大小的表格