chapter three

3 Math basics for CSS

 

This chapter covers

  • CSS measurement units
  • Calculating values in CSS
  • CSS math functions and variables
  • The math of CSS inheritance
  • The mathematics of the box model

CSS is, in a word, tricky. You carefully hand-code each declaration, combine them with precision into a style rule, refresh your browser, and the result is all too often an unholy mess that looks nothing like the clean, professional design you imagined in your head. Welcome to the frequently frustrating, always adventuresome world of CSS!

It’s true that CSS can make even the most Zen-like designer become a puller-of-hair or a gnasher-of-teeth. But if you’ve come to believe that wrestling with CSS is a no-win situation, may I offer some good news? Many, perhaps even most, CSS problems are math related and eminently fixable. Surely, there must be a catch! And there is! You have to learn the basics of how CSS uses math, which is what this chapter is all about. Here you’ll learn all about CSS measurement units and operators, the most useful CSS math functions, how to wield CSS variables in math operations, the ins and outs of box model math, and much more.

3.1 The math of CSS measurement units

3.1.1 Unit conversion math

3.1.2 The cascading calculations of em units

3.1.3 Percentage computation rules

3.1.4 Viewport units and their responsive calculations

3.1.5 Mixing units with calc()

3.1.6 Combining units requires attention to scale

3.2 CSS math functions

3.2.1 CSS arithmetic operators

3.2.2 Evaluating expressions with calc()

3.2.3 Setting limits with min(), max(), and clamp()

3.2.4 More CSS math functions

3.3 CSS variables in math operations

3.3.1 Basic usage

3.3.2 Mixing units with variables

3.3.3 Fallbacks and missing variables

3.4 The math of CSS inheritance

3.4.1 The inheritance cascade formula

3.4.2 Which properties inherit mathematically?