On https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing#values I read that content-box
should be the default box-content
mode ("as specified by the CSS standard"). However, for <button>
, I see border-box
(both in the devtools and in the rendered result) both in Chrome and Firefox.
I use the following HTML to test it. Why are the green areas not the same length?
I noticed that <button>
has display: inline-block
and thought that may be related, but no – even if I set the same display
for a <div>
, it still doesn't change the box-sizing
automatically.
<html>
<style>div, button {background: green; width: 100px; padding: 0 30px;}</style>
<body>
<div>ha</div>
<button>bu</button><br>
<div style="display: inline-block">ga</div>
</body>
</html>
CodePudding user response:
MDN has this to say:
box-sizing - CSS: Cascading Style Sheets | MDN
box-sizing: border-box
is the default styling that browsers use for the<table>
,<select>
, and<button>
elements, and for<input>
elements whose type isradio
,checkbox
,reset
,button
,submit
,color
, orsearch
.
This is documented in the standards:
CSS Box Sizing Module Level 3
Note: Certain HTML elements, such asbutton
, default toborder-box
behavior.
So technically, the "why" is because it's what the standards say it should be.
If you want to know why the standards say that, you may be able to find the answer buried in the W3C mailing list archives.
CodePudding user response:
Changing the display property will not affect the box-sizing property.
It explicitly mentioned in MDN that border-box is the default for box-sizing in the docs https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing
In the ha and ga box(1st and the 3rd). It is div, so box-sizing defaults to content-box which means
content-width = 100px
padding-left = 30px
padding-right = 30px
which implies that,
total-width = 100px 30px 30px = 160px
While in the bu box(2nd box) the box-sizing defaults to border-box, which means
total-width = 100px
padding-left = 30px
padding-right = 30px
which implies that,
content-width = 100px - 30px - 30px = 40px
please feel free to reference the BOX model diagram (https://www.w3schools.com/css/css_boxmodel.asp) to follow the following,
In border-box,
width = content-width padding-left padding-right border-left border-right
while in content-box,
width = content-width
So you can choose your box-sizing property accordingly to fit your requirement.