2
votes

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?

2
@user2253835: It says right in the title: "block formatting context".BoltClock

2 Answers

2
votes

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.

1
votes

I'm absolutely agreed with @BoltClock

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.

But I'm giving you here the solution if you want to solve that problem as what you want. Just add overflow: hidden; to your second div which won't collapse the margin.

<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; overflow: hidden;'>
    <div style='margin:20px;background:red;'>why?</div>
</div>