Math Functions in CSS
? Math Functions in CSS
CSS supports several math functions that let you perform calculations directly in your stylesheets. This helps create dynamic, responsive layouts without hardcoding values.
Key CSS Math Functions
| Function | Description | Example |
|---|---|---|
calc() | Performs calculations with mixed units | width: calc(100% - 50px); |
min() | Returns the smallest value among arguments | width: min(50vw, 300px); |
max() | Returns the largest value among arguments | width: max(200px, 10vw); |
clamp() | Clamps a value between a min and max | font-size: clamp(1rem, 2vw, 2rem); |
1. calc()
Allows addition (
+), subtraction (-), multiplication (*), and division (/).Useful for mixing relative and absolute units.
.container { width: calc(100% - 100px); height: calc(50vh + 20px);}2. min()
Takes multiple values and uses the smallest one.
.box { width: min(300px, 50vw);}3. max()
Takes multiple values and uses the largest one.
.box { width: max(150px, 20vw);}4. clamp()
Takes three values: min, preferred, max.
Ensures a value stays within a range.
p { font-size: clamp(1rem, 2vw, 2rem);}This means font size will never go below 1rem, scale with viewport width, and never exceed 2rem.
Why Use Math Functions?
Create flexible, responsive designs.
Combine different units easily.
Avoid media queries for simple size adjustments.
Make your CSS more maintainable and adaptable.
Want examples using math functions for layouts, typography, or responsive design?