Math for flexible sizes
Definition and purpose
CSS math functions combine compatible numeric values and let sizes respond to context. calc() evaluates arithmetic, min() chooses the smallest argument, max() the largest, and clamp(minimum, preferred, maximum) bounds a preferred value.
Arithmetic and comparisons
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> .parent { width: 240px; } #a { width: calc(100% - 40px); } #b { width: min(50%, 100px); } #c { width: max(50%, 100px); } </style> </head> <body> <div class="parent"> <div id="a">A</div> <div id="b">B</div> <div id="c">C</div> </div> </body></html>The three widths are 200px, 100px and 120px respectively.
Syntax and mental model
For width, calc(100% - 20px) subtracts a length from a resolved percentage. Put spaces around binary + and -. clamp(100px, 50%, 200px) chooses the preferred half width when within bounds; if the minimum exceeds the maximum, the minimum wins. Numbers, times and lengths are not freely interchangeable; use the expected result type. Advanced typed arithmetic appears later.
Bound a responsive width
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style>#a { width: clamp(100px, 40vw, 300px); }</style> </head> <body> <div id="a">Panel</div> </body></html>40vw gives 150px at 375px; the upper bound limits the larger viewport to 300px.
Common mistakes
Do not confuse min with a minimum bound: min selects the smaller value and can limit a maximum width. Avoid invalid mixed types such as calc(10px + 1s). Test sizing at narrow widths and when users enlarge text.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Viewport and container units overview. Next lesson: Other dimensions and URL values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Math for flexible sizes — knowledge check
Five questions on math for flexible sizes.
What is calc(100% - 20px) in a 200px width context?
Which function picks the smaller of two lengths?
What is clamp(100px, 250px, 200px)?
What is wrong with calc(10px + 1s) for width?
Which syntax is valid for subtraction?