问题
From the CSS Display Module Level 3 specs there is a note about block container
that says:
Note: A block container box can both establish a block formatting context and an inline formatting context simultaneously.
How is this possible conceptually?
And how are children boxes laid out then? For example, if we have both inline-level and block-level boxes inside block container, which formatting context is used in that case? Are both formatting contexts used at the same time or one of them "wins" and the other one is put aside?
回答1:
It's entirely possible, and even necessary for certain CSS rules. The easiest way to understand this is with an example of such a box.
<div style="overflow:auto">hello world</div>
Here we have an element with display:block
(by default for div elements) and overflow:auto
. This is one way that an element's rendered box will establish a block formatting context. This affects, for example, how the box's location and dimensions are affected by the presence of floats.
Compare these two examples:
.formatting.contexts {
overflow:visible;
}
.container {
width:70px;
}
img {
float:left;
margin-right:3px;
}
<div class="container">
<img src="http://placehold.it/16" alt="placeholder grey square less than one line in height">
<div class="formatting contexts">hello world</div>
</div>
.formatting.contexts {
overflow:auto;
}
.container {
width:70px;
}
img {
float:left;
margin-right:3px;
}
<div class="container">
<img src="http://placehold.it/16" alt="placeholder grey square less than one line in height">
<div class="formatting contexts">hello world</div>
</div>
In the first example, the text wraps underneath the image. That's because the div with class "formatting contexts" has overflow:visible
, so it doesn't form a block formatting context.
However, it contains only inline boxes - formed by the text content. So by the CSS rules, it establishes an inline formatting context. The text content can therefore be laid out horizontally in line boxes within this context. It is the first line box which is shrunk to avoid overlapping with the float.
In the second example, the text does not wrap underneath the image. That's because the div with class "formatting contexts" now has overflow:auto
which means that it establishes a block formatting context, and it is the block box that is shrunk to avoid it overlapping the float. But its contents are just the same, just inline boxes, so it also establishes an inline formatting context.
来源:https://stackoverflow.com/questions/56238082/how-can-block-container-establish-both-block-and-inline-formatting-contexts-at-t