What is clamp in CSS: Definition, Usage, and Examples
clamp() function in CSS lets you set a value that adjusts between a minimum, a preferred, and a maximum size. It helps create flexible layouts by automatically choosing a value within a range based on the available space.How It Works
Imagine you want a box to be at least a certain size but never too big, and you want it to grow or shrink smoothly depending on the screen size. The clamp() function does exactly that by taking three values: a minimum, a preferred (or ideal), and a maximum.
Think of it like a thermostat for your CSS values. It keeps the value from going below the minimum or above the maximum, but tries to use the preferred value if possible. This makes your design flexible and responsive without complicated calculations.
Example
This example shows how to use clamp() to set a font size that grows on bigger screens but never gets too small or too large.
body {
font-size: clamp(1rem, 2vw, 2rem);
font-family: Arial, sans-serif;
padding: 1rem;
}
p {
max-width: 600px;
margin: auto;
line-height: 1.5;
}When to Use
Use clamp() when you want to create responsive designs that adapt smoothly to different screen sizes without media queries. It is great for font sizes, widths, heights, margins, and padding where you want limits but also flexibility.
For example, you can use it to keep buttons readable on small phones but not too big on large desktops, or to make columns resize nicely in a grid layout.
Key Points
- clamp() takes three values: minimum, preferred, and maximum.
- It helps create flexible, responsive CSS without complex calculations.
- Works well for font sizes, spacing, and layout dimensions.
- Supported in all modern browsers.
Key Takeaways
clamp() sets a value that stays between a minimum and maximum while preferring a middle value.