CSS: 100% font size - 100% of what?

前端 未结 9 656
梦毁少年i
梦毁少年i 2020-11-30 17:35

There are many articles and questions about percentage-sized vs other-sized fonts. However, I can not find out WHAT the reference of the percent-value is supposed to be. I u

相关标签:
9条回答
  • 2020-11-30 18:02

    The browser default which is something like 16pt for Firefox, You can check by going into Firefox options, clicking the Content tab, and checking the font size. You can do the same for other browsers as well.

    I personally like to control the default font size of my websites, so in a CSS file that is included in every page I will set the BODY default, like so:

    body {
        font-family: Helvetica, Arial, sans-serif;
        font-size: 14px
    }
    

    Now the font-size of all my HTML tags will inherit a font-size of 14px.

    Say that I want a all divs to have a font size 10% bigger than body, I simply do:

    div {
        font-size: 110%
    }
    

    Now any browser that view my pages will autmoatically make all divs 10% bigger than that of the body, which should be something like 15.4px.

    If I want the font-size of all div's to be 10% smaller, I do:

    div {
        font-size: 90%
    }
    

    This will make all divs have a font-size of 12.6px.

    Also you should know that since font-size is inherited, that each nested div will decrease in font size by 10%, so:

    <div>Outer DIV.
        <div>Inner DIV</div>
    </div>
    

    The inner div will have a font-size of 11.34px (90% of 12.6px), which may not have been intended.

    This can help in the explanation: http://www.w3.org/TR/2011/REC-CSS2-20110607/syndata.html#value-def-percentage

    0 讨论(0)
  • 2020-11-30 18:02

    It's relative to default browser font-size unless you override it with a value in pt or px.

    0 讨论(0)
  • 2020-11-30 18:11

    According to ALL THE SPECS DATING BACK TO 1996, percentage values on font-size refer to the parent element's (computed) font-size.

    <style>
    div {
      font-size: 16px;
    }
    span {
      font-size: 75%;
    }
    </style>
    <div><span>this font size is 12px!</span></div>
    

    It's that easy.

    What if the div declares a relative font-size, like ems, or even worse, another percentage?? See “computed” above. Whatever absolute unit the relative unit converts to.

    The only question that remains is what happens when you use a percentage value on the root element, which has no parent:

    html {
      font-size: 62.5%; /* 62.5% of what? */
    }
    

    In that case, see the “duplicate” of this question. TLDR: percentages on the root element refer to the browser default font size, which might be different per user.

    References:

    • CSS 1 spec (1996)
    • CSS 2.1 spec (2011)
    • CSS Fonts Level 3 spec (2013)
    • CSS Fonts Level 3 editor’s draft (2017)
    0 讨论(0)
提交回复
热议问题