How to use BFC to clear CSS floats and resolve issues with margin merging

1. The most basic layout unit of CSS

  Box is  the object and basic unit of CSS layout.  

  The type of the element and the display property determine the type of the Box.

 

 

 2、BFC

   BFC (Box Formatting Context) is an independent rendering area that specifies how internal elements are laid out and has nothing to do with external elements.

   Formatting context is a concept in the W3C CSS2.1 specification. It is a rendering area in a page and has its own set of rendering rules that dictate how internal child elements are positioned, and how they relate and interact with other elements.

3. Layout rules of BFC

  • The inner Boxes are placed vertically one after the other.
  • The vertical distance of the Box is determined by margin. The upper and lower margins of two adjacent Boxes belonging to the same BFC will overlap.
  • The left side of each element's margin box touches the left side of the containing block's border box. Even with floats.
  • The area of ​​the BFC does not overlap 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, and vice versa.
  • When calculating the height of the BFC, floating elements also participate in the calculation.

4. Which elements will generate BFC?

  • root element;
  • float property is not none;

  • position is absolute or fixed;

  • display 为 inline-block,table-cell,table-caption,flex,inline-flex;

  • overflow is not visible; 

 5. The role and principle of BFC

  Adaptive two-column layout: fixed width and height on the left, adaptive on the right.
    Float on the left, and then overlap left and right. According to the third and fourth rules of BFC, set the element on the right to BFC.

  Clear internal floating:
    There are two floating elements in an element, and the default height of the parent element is not to calculate the height of the floating element.
    Solution, according to Article 6 of the BFC Rules.

  Prevent vertical margin stacking:
    The margins of adjacent elements inside the BFC will stack.
    According to Article 5 of the BFC rules, one of them can be set as BFC.

 

BFC is an isolated and independent container on the page, and the child elements inside the container will not affect the elements outside. And vice versa.

  

 

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325250887&siteId=291194637