3 Math basics for CSS

 

This chapter covers

  • Working with CSS measurement units
  • Calculating values in CSS
  • Using the CSS math functions and variables
  • Understanding the math of CSS inheritance
  • Getting to know the math of the box model

CSS is, in a word, tricky. You carefully hand-code each declaration, combine them with care into a style rule, refresh your browser, and the result is all-too often an unholy mess that looks nothing like the clean and professional design you imagined in your head. Welcome to 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, then may I offer some good news: many, perhaps even most, CSS problems are math-related and are eminently fixable. Surely there must be a catch! There is: You have to learn the basics of how CSS uses math, which is what this chapter is all about. Here you 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?

3.4.3 Percentage values and the inheritance math

3.4.4 The em unit inheritance multiplier

3.4.5 Solving the heading size puzzle

3.4.6 Computed values versus inherited values

3.5 Box model math

3.5.1 The default box model formulas

3.5.2 How the box-sizing property affects the box model formulas

3.5.3 Margin math and collapsing

3.5.4 Percentages and the box model

3.5.5 Using calc() for precise box model math

3.6 Solutions to Exercises

3.7 Summary