Normal flow comes first
Before flex and grid there was flow, and it is still the default and still correct for most of a page. A lot of layout code exists to recreate what flow already did.
Give a browser some HTML and no CSS at all and it lays it out. Block elements stack vertically and fill the width available. Inline elements sit in a line and wrap at the edge. Text flows. That is normal flow, it has existed since the beginning, and for an article, a form, a blog post or a documentation page it is very close to correct before you write anything.
This matters because a lot of layout code is not adding capability, it is recreating the default at greater expense. A display: flex; flex-direction: column on a container of paragraphs does approximately what block layout already did, except now margin collapsing is off, float behaves differently, and a future developer has to work out which properties are load-bearing. Reach for a layout engine when you need something flow cannot do: side-by-side, alignment on the cross axis, distribution of leftover space, two-dimensional placement.
Two concepts from flow are worth carrying into everything else. The first is the block formatting context, an independent layout region. Floats inside it do not escape, margins inside it do not collapse with anything outside it, and it does not overlap floats outside it. You create one with overflow other than visible, with display: flow-root (which exists purely to do this cleanly), and implicitly with every flex or grid container.
The second is inline layout, which is stranger than it looks and explains a whole family of bugs. Inline boxes are laid out on a line box whose height is driven by line-height, and they sit on a baseline. This is one reason an <img> in a <div> has a mysterious few pixels of space underneath it, the image is sitting on the text baseline, and the gap is the descender space for text that is not there. display: block or vertical-align: middle on the image removes it, and now you know why rather than just which incantation works.
The habit to build: start with no layout CSS, add the smallest thing that fixes what is actually wrong, and stop. It is easy to tell whether you have the habit, delete a layout declaration at random from your own stylesheet and reload. If nothing changes, that declaration was decoration, and there are probably twenty more like it.
You should now be able to
- Explain what normal flow does without any layout CSS
- Say when reaching for flex or grid is premature
- Describe what a block formatting context is and when you need one
- Recognise layout code that is fighting the default rather than using it
Loading…