Explain your understanding of the box model and how you would tell the browser in CSS to render your layout in different box models.
Importance
High
Quiz Topics
CSS
The CSS box model describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model. Each box has a content area (e.g. text, an image, etc.) and optional surrounding padding, border, and margin areas.
The CSS box model is responsible for calculating:
- How much space a block element takes up.
- Whether or not borders and/or margins overlap, or collapse.
- A box's dimensions.
Box Model Rules
- The dimensions of a block element are calculated by
width,height,padding,borders. - If no
heightis specified, a block element will be as high as the content it contains, pluspadding(unless there are floats, for which, see describe floats and how they work). - If no
widthis specified, a non-float-ed block element will expand to fit the width of its parent minus thepadding, unless it has amax-widthproperty set, in which case it will be no wider than the specified maximum width.- Some block-level elements (e.g.
table,figure, andinput) have inherent or default width values, and may not expand to fill the full width of their parent container. - Note:
spanis an inline-level element and does not have a default width, so it will not expand to fit.
- Some block-level elements (e.g.
- The
heightof an element is calculated by the content'sheight. - The
widthof an element is calculated by the content'swidth. - By default (
box-sizing: content-box),paddings andborders are not part of thewidthandheightof an element.
Note that margins are not counted towards the actual size of the box. It affects the total space that the box will take up on the page, but only the space outside the box. The box's area stops at the border — it does not extend into the margin.
Extra
Look up the box-sizing property, which affects how the total heights and widths of elements are calculated.
box-sizing: content-box: This is the default value ofbox-sizingand adheres to the rules above.box-sizing: border-box: Thewidthandheightwill include the content, padding and border, but not including the margin. This is a much more intuitive way to think about boxes and hence many CSS frameworks set* { box-sizing: border-box; }globally, so that all elements use such a box model by default. See the question onbox-sizing: border-boxfor more information.