From W3C and MDN I know that a block formatting context is created by one of the following:
display: inline-block
)display: table-cell
, which is the default for HTML table cells)display: table-caption
, which is the default for HTML table captions)visible
display: flex
or inline-flex
)But I have a question regarding the following code:
<div style='background:grey;border:black 1px dotted;width:400px'>
<div style='margin:20px;background:red;'>the parent create a bfc</div>
</div>
<div style='background:grey;width:400px'>
<div style='margin:20px;background:red;'>why?</div>
</div>
The first div element creates a BFC, but the only difference between them is that the first div has a border. Why?
Neither of the two div
elements is creating its own BFC. There is absolutely nothing in your code that suggests that the first div
element is creating its own BFC — having a border alone does not cause an element to establish its own BFC.
What the border is doing is blocking margin collapse. This means the margins of the child element do not combine with those of the parent element; they're constrained within the parent element box.