The preface
CSS box model is the most important part of CSS, in the development of difficult to understand the phenomenon, often because of the lack of understanding of the model. Box models mainly include standard model and IE model. This paper mainly describes:
- Basic concepts of the Standard Model
- Differences between the Standard model and IE model
- Margins overlap with BFC
- other
Basic concepts of the Standard Model
The standard model “Default: box-sizing: Content-box” consists of four parts, from inside to outside:
- Content area “Content” : The area where elements such as text and images can be placed. The general setting width and height refers to the width and height of the content.
- Padding area: The distance between the content and the border
- Border area “border” : is the border
- Margin area “margin” : Limited by the outer margin, the border area is extended with white space to separate adjacent elements.
Differences between the Standard model and IE model
Box-sizing is set to content-box; width and height are set to content-box. The IE model refers to the box model with box-sizing as border-box. Width and height is content+padding+border;
Margins overlap with BFC
There are three cases of external overlap:
- Between adjacent elements
- Between the parent element and its first or last word element
- Empty block-level elements
BFC
For definition of BFC, see MDNBFC
Functions of BFC:
- Make the floating content equal to the surrounding content. When the floating content overflows the container, create a CONTAINER BFC to wrap the floating content.
- Margin trap When margins are merged, separate BFC is created to solve the problem. The parent element is merged with the top margin of the first element, creating separate BFC for the parent element and the first element
other
Contains the effects of blocks
When we set elements’ attributes, such as width, height, padding, margin, and the positioning offset of “top, left”, we are often affected by the inclusion block.
Who is your containing block
- The position attribute is static, and the relative contains the nearest ancestor block element.
- The position attribute is absolute and contains ancestors whose blocks are not static, which is similar to positioning.
- Position is fixed, and the block that contains it is viewport, which is the entire screen size
The “top, left” percentage of the element’s width, padding, margin, and positioning offset is calculated based on the width of the contained block
How to draw a square with adaptive width and height
div{
width: 100%;
padding-bottom: 100%;
}
Copy the code
Since the padding and width are calculated based on the width of the contained block, and height = Content + padding, this creates a square.
reference
Layout and contain blocks
The box model
Block formatting context