The browser creates a rectangle for each element in the HTML document. The Box Model describes how the padding, border, and margin are added to the content to create this rectangle.
Diagram from CSS2.2 Working Draft
The perimeter of each of the four areas is called an edge. Each edge defines a box.
padding
property. If there is no padding
width defined, the padding edge is equal to the content edge.border
property. If there is no border
width defined, the border edge is equal to the padding edge.margin
property. If there is no margin
width defined, the margin edge is equal to the border edge.div {
border: 5px solid red;
margin: 50px;
padding: 20px;
}
This CSS styles all div
elements to have a top, right, bottom and left border of 5px
in width; a top, right, bottom and left margin of 50px
; and a top, right, bottom, and left padding of 20px
. Ignoring content, our generated box will look like this:
Screenshot of Google Chrome's Element Styles panel
padding
property (40px by 40px).border
property (50px by 50px).margin
property (giving our element a total size of 150px by 150px).Now lets give our element a sibling with the same style. The browser looks at the Box Model of both elements to work out where in relation to the previous element's content the new element should be positioned:
The content of each of element is separated by a 150px gap, but the two elements' boxes touch each other.
If we then modify our first element to have no right margin, the right margin edge would be in the same position as the right border edge, and our two elements would now look like this: