问题
I have a div with a letter :
HTML
<div>A</div>
CSS
div {
border: 1px solid black;
background-color: #CC0000;
width: 150px;
height: 150px;
margin: 10px 5px 5px 50px;
padding: 0px 30px 0px 10px /* I want to move my letter with it */
}
The letter moves due to padding property, but it also makes the square larger. Why does padding transform the square into a rectangle?
JSF : http://jsfiddle.net/fnBaD/1
回答1:
Padding is always applied 'within' the element. Hence,
padding:5px;
is effectively adding 5px on all four sides 'within' an element.
Hence, the padding property makes elements larger.
回答2:
The standard 'box model' does NOT include padding/borders into width/height calculations
By adding the box-sizing:border-box property it will force the browser to INCLUDE the padding/borders in the dimensions
It's often seen in a universal selector
* {
box-sizing:border-box;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing
回答3:
Padding is considered to be part of the element it is applied to. This is why the element gets larger.
来源:https://stackoverflow.com/questions/24354838/why-does-padding-property-make-elements-larger