http://learn.shayhowe.com/html-css/opening-the-box-model/
Working with the Box Model
Every element is a rectangular box, and there are several properties that determine the size of that box. The core of the box is defined by the width and height of an element, which may be determined by the
display
property, by the contents of the element, or by specified width
and height
properties. padding
and then border
expand the dimensions of the box outward from the element’s width and height. Lastly, anymargin
we have specified will follow the border.
Each part of the box model corresponds to a CSS property:
width
, height
, padding
,border
, and margin
.
Let’s look these properties inside some code:
1 2 3 4 5 6 7 8 | div { border: 6px solid #949599; height: 100px; margin: 20px; padding: 20px; width: 400px; } |
According to the box model, the total width of an element can be calculated using the following formula:
1 2 | margin-right + border-right + padding-right + width + padding-left + border-left + margin-left |
In comparison, according to the box model, the total height of an element can be calculated using the following formula:
1 2 | margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom |
Using the formulas, we can find the total height and width of our example code.
- Width:
492px = 20px + 6px + 20px + 400px + 20px + 6px + 20px
- Height:
192px = 20px + 6px + 20px + 100px + 20px + 6px + 20px
The box model is without question one of the more confusing parts of HTML and CSS. We set a
width
property value of 400
pixels, but the actual width of our element is 492
pixels. By default the box model is additive; thus to determine the actual size of a box we need to take into account padding, borders, and margins for all four sides of the box. Our width not only includes the width
property value, but also the size of the left and right padding, left and right borders, and left and right margins.
No comments:
Post a Comment