1. Brief summary
- Block level boxes will participate in the formation of BFC: for example, the display value is block/ list-item/ table
- Inline level boxes will participate in the formation of IFC: for example, the display value is inline/ inline-table/ inline-block
2、FC(Formatting Context)
Formatting context. It defines a rendering area in the page and has a set of rendering rules. It determines how its child elements will be positioned, as well as the relationship and interaction with other elements.
3. Layout rules
- IFC layout rules: In the context of inline formatting, boxes are arranged horizontally one after another, starting from the top of the containing block.
- The margin border padding in the horizontal direction is retained between the boxes
- It can be aligned in different ways in the vertical direction: top or bottom alignment, or based on the baseline of the text
- BFC layout rules:
- The inner boxes will be vertically placed one after another
- The vertical distance of the box is determined by the margin, and the margins of two adjacent boxes belonging to the same BFC will overlap
- The left outer edge (margin-left) of each element is in contact with the left side of the containing block (for left-to-right formatting). This is true even if there is a float, unless the element forms a new BFC by itself
- The BFC area will not overlap with the float box
- BFC is an isolated and independent container on the page, the child elements inside the container will not affect the outside elements
- When calculating the height of the BFC, floating elements also participate in the calculation
4. How to form a BFC
- Root element or other elements that contain it
- Floating element (float is not none)
- Absolutely positioned element (position is absolute or fixed)
- Non-block-level elements have display: inline-block, table-cell, table-caption, flex, inline-flex
- The block-level element has overflow and the value is not visible
5. The use of BFC
- Clear float: When the parent box div has not set the height, and the child boxes are all set to float, the parent element will collapse in height. Solution: Add to the parent element
overflow:hidden
to form a BFC. When calculating the height, the height of the float element will be calculated to achieve the effect of eliminating the effect of floating. - Layout: adaptive two-column layout.
Solution: set the mainoverflow:hidden
to form a BFC, because the BFC area is independent, will not interact with other elements on the page, and will not overlap with the float element, so it can form a two-column adaptive layout
- Prevent vertical margin merging.
Solution: Wrap a layer of elements outside one of the elements and setoverflow:hidden
it to form a BFC. Because the BFC is an independent container inside, it will not interact with the outside and can prevent margin merging.