CodeBlanks Logo Icon CodeBlanks

calc() function

CSS course · Beginner · Lesson 63/82

Learn mathematical calculations with calc().

What is calc()?

The calc() function combines different units with math. Write width: calc(100% - 4rem) and the browser computes the percentage and the rem together.

Operators are + - * /. For addition and subtraction, spaces around the operator are required; for multiplication and division, units are used carefully.

Operators and spaces

Inside calc(), + and - must be wrapped in spaces. calc(100% - 32px) is correct; calc(100%-32px) is wrong.

For multiplication and division one side must be a unitless number: calc(2rem * 3) or calc(100% / 4). Multiplying two lengths is invalid.

Multiplication and division

With calc() you can multiply a length by a number or divide a length by a number. calc(1.5rem * 2) gives 3rem; calc(100% / 3) is handy for three equal columns.

The number must be unitless; you cannot multiply two lengths. Even with rounding, the browser turns the result into pixels.

Exercise calc for a panel

Write a .panel selector. Set its width to calc(100% - 4rem) and its padding to calc(1rem + 8px).

Show example solution
/* add the panel section */
.panel {
  width: calc(100% - 4rem);
  padding: calc(1rem + 8px);
}

Test yourself

  1. Which calc() writing is valid?

    /* spaces are required around + and - */
    • calc(100% - 50)
    • calc(100% -50px)
    • calc(100%-50px)
    • calc(100% - 50px)
    Show answer

    calc(100% - 50px) — Correct. + and - need spaces around them: calc(100% - 50px).

  2. Width with calc

    .panel {
      width: calc(____ - 2rem);
    }
    Show answer
    .panel {
      width: calc(100% - 2rem);
    }
  3. Match each operator to its meaning

    +
    Addition
    -
    Subtraction
    *
    Multiplication
    /
    Division

All lessons in Beginner