Why do a div and a button with the same styles render at different sizes?

旧城冷巷雨未停 提交于 2019-12-30 17:20:09

问题


I have a page with some clickable <div> elements, and I want to change them to <button>s instead to make it easier to identify them via jQuery. But when I change the <div>s to <button>s, their size changes. (I'm styling them as fixed width and height, but the button renders at a different width and height than the div does.)

Here's a jsfiddle that reproduces the problem: http://jsfiddle.net/AjmGY/

Here's my CSS:

.styled {
    border: 4px solid black;
    background: blue;
    width: 100px;
    height: 100px;
}

And my HTML:

<div class="styled"></div>
<button class="styled"></button>

I would expect to see two boxes of identical size, but the bottom box (the <button>) is noticeably smaller. This behavior is consistent across all the browsers I tried it on, both Windows (Chrome, FireFox, IE, Opera) and Android (built-in browser and Dolphin).

I tried adding display: block; to the style, thinking that that might make them both render using the same rules (i.e., make the button render like a div since it's a block element now), but that had no effect -- the button remained smaller.

As I increase the border width, the disparity increases. It looks as though the button's border is inside its width, rather than above and beyond its width as with the <div>. As far as I understand it, this violates the box model, though the W3C does say:

user agents may render borders for certain user interface elements (e.g., buttons, menus, etc.) differently than for "ordinary" elements.

Is it normal / documented / expected behavior for a button to have its border on the inside of its width and height, rather than outside? Can I rely on this behavior?

(My page uses an HTML5 doctype, if that's relevant.)


回答1:


Buttons and other input controls are rendered using the border-box model by default; i.e. content, padding and border all add up to the total width that you declare. They also often have some padding added by browsers arbitrarily according to their default stylesheets. As you quote, this is acceptable behavior and not a violation of standards; it's simply to accommodate rendering of OS-level GUI controls.

To get your button to be the same size as your div, size it according to the content-box model (which is "the" original W3C box model) and zero out its padding:

button.styled {
    -moz-box-sizing: content-box;
    -webkit-box-sizing: content-box;
    box-sizing: content-box;
    padding: 0;
}

jsFiddle demo



来源:https://stackoverflow.com/questions/8395349/why-do-a-div-and-a-button-with-the-same-styles-render-at-different-sizes

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