Search code examples
htmlcssborder

Is a block formatting context created by an element with a border?


From W3C and MDN I know that a block formatting context is created by one of the following:

  • the root element or something that contains it
  • floats (elements where float is not none)
  • absolutely positioned elements (elements where position is absolute or fixed)
  • inline-blocks (elements with display: inline-block)
  • table cells (elements with display: table-cell, which is the default for HTML table cells)
  • table captions (elements with display: table-caption, which is the default for HTML table captions)
  • elements where overflow has a value other than visible
  • flex boxes (elements with 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?


Solution

  • 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.