When a relative line-height is inherited, it is not relative to the element's font-size. Why? And how do i make it relative?

十年热恋 提交于 2019-12-10 12:38:54

问题


I have a global reset that sets font-size and line-height to inherit for every element:

* {
  font-size:   inherit;
  line-height: iherit; }

For html, i define them explicitly:

html {
  font-size:   16px;
  line-height: 1.25em; } /* 16×1.25 = 20 */

Note, that line-height is set in a relative unit.

For h1, i define different font-size:

h1 {
  font-size: 4em; }

I expect h1 to inherit the relative line-height of 1.25em. The resulting line-height should be equal to 80px (16×4×1.25).

But in reality h1's line-height remains equal to 20px (that's the same as html's: 16×1.25=20).

Say, i have the following HTML:

<p>foo<br>bar</p>
<h1>foo<br>bar</h1>

Screenshot of the result:

http://jsfiddle.net/M3t5y/5/

To work around this problem, i have to define h1's line-height explicitly equal to the same value that it inherits:

h1 {
  font-size:   4em;
  line-height: 1.25em; }

Then line-height becomes correct:

http://jsfiddle.net/M3t5y/6/

It looks like the relative value is first calculated into the absolute value and then the absolute value is inherited. Or maybe it is inherited relative to the parent's font-size, not the element's font-size.

Questions

  1. Why is the relative line-height inherited incorrectly?
  2. How do make the relative line-height be inherited as a value relative to the element's font-size, not its parent's?

PS There's a question with a similar problem in its title, but it is different in detail.


回答1:


When you use em values for line height, the value of the line height is computed, and it is that computed value which is also used by child elements.

If you use a bare number instead, it is the ratio that is used for the calculation of child element line-heights.

So use line-height:1.25; instead of line-height:1.25em;




回答2:


line-height is calculated on the element and then that element is inherited when you use em. If you inspect your first example you'll notice that the computed value for line-height is 20px (16x1.25), not 1.25em.

You can use line-height:1.25 and it will be computed on the correct element.



来源:https://stackoverflow.com/questions/15586245/when-a-relative-line-height-is-inherited-it-is-not-relative-to-the-elements-fo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!