[css interview questions] Deeply understand BFC, it’s actually not that difficult

What is BFC

Block Formatting Context (BFC) is a part of the visual CSS rendering of a Web page. It is an area where block-level boxes are generated during the layout process, and it is also a limited area for interaction between floating elements and other elements.

BFC is an independent layout environment, which can be understood as a container in which items are placed according to certain rules without affecting external elements.

Create a rule:

  1. root element;
  2. float (element with value left/right)
  3. position (element with absolute/fixed value)
  4. display (an element whose value is one of inline-block, table-cell, table-caption, flex, inline-flex)
  5. overflow (element with value auto/hidden)

Its features:

  1. Elements inside the container will not affect elements outside
  2. The inner boxes will be placed one after another in the vertical direction, starting from the top
  3. The vertical distance of the Box is determined by margin. The margins of two adjacent boxes belonging to the same BFC will overlap regardless of the direction.
  4. The area of ​​BFC will not overlap the floating element, but will be close to the floating element.

What it does:

  1. Vertical margin overlap issue
  2. Adaptive two-column layout
  3. remove float

What is the vertical margin overlap issue?
If margins are set for both boxes, the margins of the two boxes will overlap in the vertical direction, and the one with the larger absolute value will be the final result displayed on the page.

		.box {
    
    
			background: red;
			width: 200px;
			height: 200px;
			margin: 20px;
		}
		.box2{
    
    
			margin:  30px 20px;
			background: red;
			width: 200px;
			height: 200px;
		}
		<div class="box"></div>
		<div class="box2"></div>

Insert image description here
At this time, you can wrap a div.content in the outer layer of box2 and set overflow: hidden, and use the bfc feature to achieve a spacing of 30px+20px=50px to solve the problem of margin collapse between sibling elements.

		.content{
    
    
			overflow: hidden; 
		}
		.box {
    
    
			background: red;
			width: 200px;
			height: 200px;
			margin: 20px;
		}
		.box2{
    
    
			margin:  30px 20px;
			background: red;
			width: 200px;
			height: 200px;
		}
        <div class="box"></div>
		<div class="content">
			<div class="box2"></div>
		</div> 

Insert image description here

Guess you like

Origin blog.csdn.net/qq_39078783/article/details/127144783
Recommended