CSS math functions allow you to perform calculations directly within your styles. These functions make it easier to create dynamic, flexible layouts and designs without relying on external tools or manual calculations.
Common CSS Math Functions
calc()
: Performs basic arithmetic operations (+
,-
,*
,/
).Syntax:width: calc(expression);
Example:
width: calc(100% - 50px); font-size: calc(16px + 2vw);
min()
: Chooses the smallest value from a list of values.Syntax:width: min(value1, value2, ...);
Example:
width: min(50%, 300px);
max()
: Chooses the largest value from a list of values.Syntax:width: max(value1, value2, ...);
Example:
width: max(50%, 200px);
clamp()
: Sets a value within a defined range (minimum, preferred, maximum).Syntax:width: clamp(min, preferred, max);
Example:
font-size: clamp(16px, 2vw, 24px);
Examples
1. Using calc()
for Dynamic Width
<div style="width: calc(100% - 50px); background-color: lightblue;"> Box with width calculated as 100% minus 50px </div>
2. Using min()
for Responsive Design
<div style="width: min(50%, 300px); background-color: lightgreen;"> Box with width limited to 50% or 300px, whichever is smaller </div>
3. Using max()
for Minimum Size
<div style="width: max(200px, 20%); background-color: lightcoral;"> Box with width at least 200px or 20%, whichever is larger </div>
4. Using clamp()
for Font Sizes
<p style="font-size: clamp(16px, 2vw, 24px);"> This text adjusts its size between 16px and 24px based on the viewport width. </p>
How Math Functions Work Together
Responsive Layout with calc()
and clamp()
<style> .responsive-box { width: clamp(200px, 50%, 600px); height: calc(100px + 10vh); background-color: lightyellow; } </style> <div class="responsive-box"> Responsive Box </div>
Best Practices
- Fallbacks:
- Test math functions in older browsers that may not support them.
- Use feature queries (
@supports
) if needed:@supports (width: clamp(200px, 50%, 600px)) { .box { width: clamp(200px, 50%, 600px); } }
- Combine with Variables:
- Use custom properties (CSS variables) for flexibility:
:root { --base-size: 16px; } p { font-size: calc(var(--base-size) * 1.5); }
- Use custom properties (CSS variables) for flexibility:
- Optimize for Readability:
- Keep expressions simple and well-commented for maintainability.
Experiment
Try this example:
<!DOCTYPE html> <html lang="en"> <head> <style> .box { width: calc(100% - 20px); height: clamp(100px, 10vw, 200px); background-color: lightblue; margin: 10px auto; text-align: center; line-height: clamp(100px, 10vw, 200px); font-size: clamp(16px, 2vw, 24px); } </style> </head> <body> <div class="box">Responsive Box</div> </body> </html>
This example dynamically adjusts the box size and font size based on the viewport width. Experiment with it to see how CSS math functions simplify responsive design!