An anonymous box is created when there is not an HTML element to use for the box. This situation happens when, for example, you declare display: flex
on a parent element, and directly inside there is a run of text not contained in another element. In order to fix the box tree, an anonymous box is created around that run of text. It will then behave as a flex item, however, it cannot be targeted and styled like a regular box because there is no element to target.
<div class="flex">
I am wrapped in an anonymous box
<p>I am in the paragraph</p>
I am wrapped in an anonymous box.
</div>
body {
font: 1.2em sans-serif;
margin: 20px;
}
.flex {
display: flex;
}
.flex > * {
background-color: rebeccapurple;
color: white;
}
The same thing happens when you have text runs interspersed with block elements. In the next example I have a string inside a <div>
; in the middle of my string is a <p>
element containing part of the text.
<div class="example">
I am wrapped in an anonymous box
<p>I am in the paragraph</p>
I am wrapped in an anonymous box.
</div>
body {
font: 1.2em sans-serif;
margin: 20px;
}
.example > * {
background-color: rebeccapurple;
color: white;
}
The string is split into three boxes in the box tree. The part of the string before the paragraph element is wrapped in an anonymous box, then we have the <p>
, which generates a box, and then another anonymous box.
Something to consider about these anonymous boxes is that they inherit styles from their direct parent, but you cannot change how they look by targeting the anonymous box. In my examples, I am using a direct child selector to target the children of the container. This does not change the anonymous boxes, as they are not "elements" as such.
Inline anonymous boxes are created when a string is split by an inline element, for example, a sentence that includes a section wrapped with <em></em>
. This splits the sentence into three inline boxes — an anonymous inline box before the emphasized section, the section wrapped in the <em>
element, then a final anonymous inline box. As with the anonymous block boxes, these anonymous inline boxes cannot be styled independently in the way the <em>
can; they just inherit the styles of their container.
Other formatting contexts also create anonymous boxes. Grid layout behaves in the same way as the flexbox example above, turning strings of text into a grid item with an anonymous box. Multiple-column layout creates anonymous column boxes around the columns; these also cannot be styled or otherwise targeted. Table layout will add anonymous boxes to create a proper table structure — for example adding an anonymous table row — if there was no box with display: table-row
.