5.5 Containing Block
Professor:We’ve arrived at one very important concept in CSS layout called a con-
taining block. The c ontaining block of an e le ment is basically the rectangular area in
which the element is pla ced. It can be the content box of its parent but that is not nec-
essary. The containing block is so important because every time we set the position,
or use percentages to set the dimensions of an element box, we do that relative to the
element’s containing block.
The containing bloc k for the root (that is <h tml>) element is simply the document
window, also called a viewport.
Other elements get their containing block according to the value of their position
property. If position is set to either static or relative, then the element’s con-
taining block is the content box of its nearest ancestor with block display. If, how-
ever, the element is absolutely position ed, then its containing block is define d by the
padding edge of its nearest positioned ancestor.
Mike: I assume that the containing block d oes not constrain the c ontained eleme nt.
Professor: Why do you think so?
Mike: When we set the display property of the <div> element of the example-box
class to inline on page 79, for example, the element was only partly contained in its
containing block. The containing block of the <div> element was the body’s content
box, wasn’t it?
Professor: Precisely. That is because <body > has block d isp la y and was of course the
nearest ancestor with block display of the <div> elem ent in that example. Indeed, an
element is not co nstrained by its containing block and may overflow.
And now, the tricky part. Let’s position the second element by setting its top and
left pr operties to 0:
#two {
position: absolute;
top: 0;
left: 0;
}
Where do you think the element will appear?
Maria: In th e top left corner of the body.
Professor: Yes? Could you be more precise, please? How far, for example, from the
edge of the viewport do you think it will be placed?
Maria: Wait a minute! <body> is not positioned. Because there are no other posi-
tioned ancestors, the containing block of the second elemen t is probably the viewport.
The second eleme nt will move all the way to the document window’s edge. Because
5.5. Containing Block 8 3