3 Document flow and the box model

 

This chapter covers

  • General tips for building a page layout
  • Practical advice for element sizing
  • An introduction to logical properties
  • Negative margins and margin collapsing
  • Consistent spacing of components on the page

When it comes to laying out elements on the page, you’ll find a lot of things going on. On a complex site, you may have grids, absolutely positioned elements, and other elements of various sizes. You have a lot of things to keep track of, and learning everything involved with layout can be overwhelming.

We’ll spend several chapters taking a close look at layout techniques. Before we get to those, it’s important to have a solid grasp on the fundamentals of how the browser sizes and places elements. The more advanced topics of layout are built atop concepts like document flow and the box model; these are the basic rules that determine the location and size of elements on the page.

In this chapter, you’ll build a basic one-column page layout. You may be familiar with this as a classic beginner exercise for CSS, but I’ll guide you through it in a way that highlights several often-overlooked nuances of layout. We’ll look at some of the edge cases of the box model, and I’ll give you practical advice for sizing and aligning elements.

3.1 Normal document flow

3.1.1 Centering content horizontally

3.1.2 Using logical properties

3.1.3 Adopting useful shorthand logical properties

3.2 The box model

3.2.1 Avoiding magic numbers

3.2.2 Adjusting the box model

3.2.3 Using universal border box sizing

3.3 Element height

3.3.1 Controlling overflow behavior

3.3.2 Using alternatives to percentage-based heights

3.3.3 Using min-height and max-height

3.4 Negative margins

3.5 Collapsed margins

3.5.1 Collapsing between text

3.5.2 Collapsing multiple margins

3.5.3 Collapsing outside a container

3.6 Spacing elements within a container

3.6.1 Considering changing content