4 CSS Grid math

 

This chapter covers

  • Understanding the math that underlies CSS Grid
  • Learning the Grid coordinate system
  • Grokking the Grid track sizing algorithm
  • Putting Grid’s track sizing functions to good use

It 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 — wait for it — an HTML table! It actually made a bit of sense at the time 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, which I cover in chapter 5). But the power of CSS Grid comes at the cost of increased complexity, especially as the number of page components increases. But that complexity is fundamentally a math problem because what Grid is doing behind the scenes is using math to divide up your page. When you understand that math, which is the goal of this chapter, it suddenly becomes easier to create robust and 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

4.5 Solutions to Exercises

4.6 Summary