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

时间:2014-01-27 11:06:54

标签: 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? */
}

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

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

在流畅的布局中 - 当使用字体大小的rem时 - 将是“非值”行高:2.0;使用rem中计算的字体高度作为行高还是仍然依赖于基于像素的值(在示例中是旧浏览器的后备)? 我想我应该说这是我原来的问题 - 我现在要编辑

3 个答案:

答案 0 :(得分:12)

嗯,在我看来,所有这些(<number> | <length> em | <percentage>)相对措施可能适合line-height财产。

  

<number> 使用的值是无单位<number>乘以   元素的字体大小。计算的值与指定的值相同   <number>。在大多数情况下,这是设置行高的首选方法   在继承的情况下没有意外结果。

     

<length>   指定的<length>用于计算行框高度。

     

<percentage> 相对于   元素本身的字体大小。计算出的值是这个百分比   乘以元素的计算字体大小。百分比和em   值可能会产生意外结果。

     

numberpercentageem之间的差异:

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

使用percentageem作为父元素时,会导致孩子从父母的计算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的{​​{1}}默认值为<html>,但不会对我们的计算进行任何更改。

<强> JSBin Demo

答案 1 :(得分:1)

首先,我不理解line-heightp元素的想法,因为段落中2行之间的标准边距始终存在于浏览器默认功能中。你试图实现它的方式,它只会在两行之间增加空间

提供解决方案,除非您选择media-query,否则没有标准方式,因为line-height可以使用size字体,所以更大字体大小,行高更大....这一点很重要,因为你已经设置font-size相对于视图端口维度=&gt; font-size: 1.4rem;

请在此处阅读line-height的工作原理:CSS - Line height property, how it works (simple)

修改

在您评论后进行编辑,请注意,如果您在line-height中提供p,则会添加到p内的所有内容... if you不想使用媒体查询和浏览器一致性是您的主要关注点,那么您可以这样做:

p{
  line-height: 1.2;
  padding-top: 1% /*this will ensure that p has space from above */
}

答案 2 :(得分:0)

请使用将线高乘以10并使用px作为线高。

line-height: (1.3 * 10) + px;

同时你只需使用line-height: 1.3rem;