SmartCodingTips

CSS calc() and clamp() Functions

The calc() and clamp() functions allow dynamic sizing and flexible responsiveness in CSS. They help create layouts and typography that adapt beautifully to different screen sizes.

1. Using calc()

calc() lets you perform calculations within CSS property values.


.element {
    width: calc(100% - 40px);
    margin-top: calc(2rem + 10px);
    font-size: calc(1rem + 0.5vw);
}
            

You can mix units like %, px, rem, and vw together. It's great for spacing, layouts, and typography.

2. Using clamp()

clamp() defines a value that adapts between a minimum, preferred, and maximum:


h1 {
    font-size: clamp(1.5rem, 4vw, 3rem);
}
            

In this example, the font size:

  • Never goes below 1.5rem
  • Scales based on 4vw (viewport width)
  • Never exceeds 3rem

3. When to Use

  • calc() – for combining fixed and flexible values (e.g., width: calc(100% - 300px))
  • clamp() – for responsive font sizes and elements that need fluid scaling

4. Browser Support

Both calc() and clamp() are well-supported in all modern browsers. Avoid clamp() for legacy Internet Explorer.

Conclusion

Use calc() for precision and flexibility, and clamp() for elegant responsiveness. These functions unlock powerful layout and typography capabilities in modern CSS.