The clamp() function helps you set a size that can grow and shrink but stays within limits. It keeps your design flexible and neat on different screen sizes.
0
0
Clamp function in CSS
Introduction
When you want text size to be bigger on large screens but not too small on phones.
To set a box width that adjusts but never gets too narrow or too wide.
For padding or margin that changes with screen size but stays comfortable.
When you want a responsive layout without writing many media queries.
Syntax
CSS
clamp(minimum, preferred, maximum)
minimum is the smallest value allowed.
preferred is the ideal value that can grow or shrink.
maximum is the largest value allowed.
Examples
Text size will be at least 1rem, ideally 2% of viewport width, but no bigger than 2rem.
CSS
font-size: clamp(1rem, 2vw, 2rem);
Width will be at least 200px, ideally half the container, but no more than 600px.
CSS
width: clamp(200px, 50%, 600px);
Padding adjusts with screen size but stays between 0.5rem and 1.5rem.
CSS
padding: clamp(0.5rem, 2vw, 1.5rem);
Sample Program
This page shows a heading and paragraph that change size smoothly between minimum and maximum values using clamp(). The heading grows from 1.5rem to 3rem, and the paragraph text and box size also adjust nicely.
CSS
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Clamp Function Example</title> <style> body { font-family: Arial, sans-serif; margin: 2rem; } h1 { font-size: clamp(1.5rem, 5vw, 3rem); color: #2a7ae2; } p { font-size: clamp(1rem, 2.5vw, 1.5rem); max-width: clamp(200px, 60%, 600px); background-color: #e0f0ff; padding: clamp(0.5rem, 1vw, 1rem); border-radius: 0.5rem; } </style> </head> <body> <h1>Responsive Heading</h1> <p>This paragraph uses clamp() to adjust its font size, width, and padding based on the screen size. Try resizing the browser window to see it change smoothly.</p> </body> </html>
OutputSuccess
Important Notes
Clamp works with any CSS length unit like rem, px, %, vw, vh.
It helps avoid writing many media queries for simple responsive sizing.
Use clamp() for better control over flexible layouts and typography.
Summary
Clamp sets a value that grows and shrinks but stays between a minimum and maximum.
It is great for responsive font sizes, widths, and spacing.
Clamp makes designs flexible and easier to maintain.