CSS Layout Model
Understanding CSS's layout model is key to mastering web page layout. It determines how elements are arranged on the page, how much space they occupy, and how they interact with each other. Core concepts include the box model, element display types, and positioning schemes.
The Box Model
As mentioned in the "Basic Concepts" chapter, CSS treats every HTML element as a rectangular box. This model describes the space these boxes occupy on the page.
A box consists of four parts, from inside to outside:
- Content: The actual content of the element, such as text or images. Its dimensions are defined by the
widthandheightproperties. - Padding: The transparent area surrounding the content. The
paddingproperty controls the size of this area. - Border: The lines surrounding the padding. The
borderproperty controls its style. - Margin: The transparent area surrounding the border, used to separate this element from other elements. The
marginproperty controls its size.

The box-sizing Property
By default (box-sizing: content-box;), the width and height you set only apply to the Content area. The element's total width is actually width + padding-left + padding-right + border-left + border-right. This makes layout calculations complex.
In modern CSS development, the best practice is to globally set box-sizing: border-box;. This changes the box model calculation method:
box-sizing: border-box; means the width and height you set will be the total width and total height within the border (i.e., width = content + padding + border). This way, no matter how you change padding or border, the element's total dimensions remain constant, making layout extremely intuitive and predictable.
/* A common global reset */
*,
*::before,
*::after {
box-sizing: border-box;
}Element Display Types (display)
An element's display property determines how it behaves in the layout. The two most basic types are:
Block-level Elements
display: block;- Characteristics:
- Takes up a full line, always starts on a new line.
- Width defaults to 100% of its parent container.
- Can set
width,height,margin,padding.
- Examples:
<div>,<p>,<h1>-<h6>,<ul>,<li>,<form>.
Inline-level Elements
display: inline;