chapter four

4 CSS Grid math

 

This chapter covers

  • The math that underlies CSS Grid
  • The Grid coordinate system
  • The grid track sizing algorithm
  • Putting Grid’s track-sizing functions to good use

It’s hard to even imagine it now, but there was a time not that long ago when a web designer’s go-to layout tool was an HTML table! It actually made a bit of sense back then since a table provided structure, and what web pages desperately needed in the early days was some sort of structure. Ah, but what a rigid, unforgiving scaffolding it was!

Those primitive days are happily behind us now that we have CSS Grid as the basic layout engine of the modern web (along with Flexbox, covered in chapter 5). But the power of CSS Grid comes at the cost of increased complexity, especially as the number of page components increases. Still, that complexity is fundamentally a math problem because Grid is using math behind the scenes to divide up your page. When you understand that math, which is the goal of this chapter, it becomes much easier to create robust, creative layouts and to troubleshoot any Grid layout problems that arise.

4.1 The mathematical foundations of CSS Grid

4.1.1 Foundations of the grid formatting context

4.1.2 The coordinate system approach

4.1.3 The algebraic model

4.1.4 Mathematical differences from other layout systems

4.2 The Grid coordinate system

4.2.1 The grid model

4.2.2 Span notation and its mathematical meaning

4.2.3 Working smarter with negative indexing

4.3 The grid track sizing algorithm

4.3.1 The algebra of grid line placement

4.3.2 How fr units distribute available space

4.3.3 Taking the box model into account

4.3.4 The algorithm for calculating fr unit values

4.3.5 Troubleshooting: When <flex> resolves to 0px

4.4 The math of Grid’s track-sizing functions and keywords

4.4.1 Controlling track sizes with minmax()

4.4.2 Understanding auto in grid tracks

4.4.3 The math of fit-content()

4.4.4 The repeat() function and its mathematical distribution