clamp() for Fluid Typography
The clamp() function in CSS is one of the most powerful features for creating fluid typography. With clamp(), you can set a minimum and maximum font size for text and have it scale dynamically in between those values based on the viewport width.
What is clamp()?
This function enables you to make typography that’s truly responsive, without the need for multiple fixed breakpoints. By using clamp(), you can ensure that your text will always be legible and easy to read, no matter what device it’s viewed on.
clamp(minimum, preferred, maximum);
The clamp() function takes a minimum value, a preferred value, and a maximum value. It outputs the middle value if the preferred value falls within the range set by the minimum and maximum values. Otherwise, it outputs the nearest boundary value.
- minimum: The smallest value that the property can take (e.g., the smallest font size).
- preferred: The ideal value, often based on the viewport size (e.g., scaling font size).
- maximum: The largest value that the property can take (e.g., the largest font size).
Syntax for Fluid Typography with clamp()
For fluid typography, the clamp() function is used to dynamically set the font size based on the viewport width. A common formula is:
font-size: clamp(minimum, preferred, maximum);
- minimum: The smallest font size (in px, rem, em, etc.).
- preferred: The font size that scales with the viewport width, often using a vw (viewport width) unit.
- maximum: The largest font size (in px, rem, em, etc.).
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fluid Typography with clamp()</title> <style> /* Fluid typography using clamp() */ h1 { font-size: clamp(1.5rem, 5vw + 1rem, 3rem); /* Minimum 1.5rem, preferred 5vw + 1rem, max 3rem */ margin: 0; padding: 20px; text-align: center; color: #333; } /* Body text using fluid typography */ p { font-size: clamp(1rem, 3vw + 1rem, 2rem); /* Minimum 1rem, preferred 3vw + 1rem, max 2rem */ color: #666; } </style> </head> <body> <h1>Fluid Typography with clamp()</h1> <p>This text uses the clamp() function for fluid typography. It adjusts the font size based on the viewport width, staying within defined minimum and maximum limits.</p> </body> </html>
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.