HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

CSS Math Functions

CSS math functions allow you to perform dynamic calculations to determine property values. These functions are particularly useful for building responsive layouts that adapt seamlessly to different screen sizes.


1. The calc() Function

This allows you to perform basic mathematical operations (+, -, *, /) to calculate a value. You can even mix different units (e.g., subtracting pixels from percentages).

.container {
    width: calc(100% - 100px); /* Full width minus fixed padding */
}

2. The min() and max() Functions

  • min() — Uses the smallest value among comma-separated expressions.
  • max() — Uses the largest value among comma-separated expressions.
.box {
    width: min(50%, 400px); /* Never exceeds 400px but stays 50% on small screens */
    padding: max(2rem, 10px); /* At least 2rem, but no less than 10px */
}

3. The clamp() Function

The clamp() function clamps a value between an upper and lower bound. It takes three parameters: minimum value, preferred value, and maximum allowed value.

This is revolutionary for Fluid Typography.

h1 {
    font-size: clamp(1.5rem, 5vw, 3rem);
    /* Min: 1.5rem, Prefers: 5% of screen width, Max: 3rem */
}

Tip: Always include spaces around the + and - operators in calc() (e.g., calc(100% - 10px)), otherwise the expression will fail.