Why does the <button> tag treat em differently from how a <div> does?

倖福魔咒の 提交于 2019-12-24 12:34:18

问题


I've noticed that <button> tags seem to be scaling em units from something other than the font-size. <div> tags aren't exhibiting this same behaviour. This happens across the latest versions of chrome, firefox & ie.

They are both styled like this:

button, div {
    width: 3rem;
    height: 3em;
}

See this fiddle for an example.

If I size a div and a button both with a width of 3rem and height of 3em, I would expect them to be square, unless there is a font-size style affecting one of them, or an ancestor. The only font-size is on the <body> tag, but what happens is that the div is square, but the button has a smaller height than its width.

If I inspect the button in chrome, it says that it inherits the 1em font-size from the <body> tag, and yet the problem is fixed when I set its font size to 1em explictly (see fiddle).

Can anyone explain to me what's happening here? It feels like I'm missing something obvious.


回答1:


It seems that your HTML button was not inheriting font size from <body>. I believe many form elements behave this way (at least in some browsers), though I have no documentation.

I had success by adding:

button {
    font-size:inherit;
}

WORKING EXAMPLE




回答2:


What is happening here is that browsers apply a default browser style sheet that causes reduced font size to be used for button elements. This is not described in specifications, and the amount of reduction may vary by browser. You can see the same thing happening for input elements like <input type="text"> by default: the font size is smaller than in the surrounding text (though this may be difficult to see if different font faces are used, which is a common default).

Developer Tools in browsers aren’t perfect. For example, Chrome indeed shows font-size of a button element as inherited—but is also shows the computed size as smaller. The explanation is that the browser’s default style sheet has font: -webkit-small-control for button, and this is the setting that really matters here. The information about inheritance is simply incorrect.

When you set font-size: 1em (or, equivalently, font-size: 100%) on the button element, you override the default setting. This is somewhat better than setting font-size: inherit, which has slightly less widespread browser support.



来源:https://stackoverflow.com/questions/24536160/why-does-the-button-tag-treat-em-differently-from-how-a-div-does

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