DEV Community

Cover image for Responsive fonts in CSS
Carmen Ansio
Carmen Ansio

Posted on • Updated on

Responsive fonts in CSS

Let's explore a super useful and modern technique to make our fonts responsive, using the CSS clamp() function along with custom properties. Let's get started!


Introduction to clamp()

The clamp() function in CSS is a powerful tool that allows us to set a font size (or any other property) within a specific range. This means we can have more precise control over how our content looks on different screen sizes.

 

Step 1: Define Custom Properties

First, we define the custom properties in our style sheet:

:root {
    --font-min: 16px; /* Minimum size */
    --font-max: 32px; /* Maximum size */
    --font-preferred: 2vw; /* Preferred size */
}
Enter fullscreen mode Exit fullscreen mode

These variables will allow us to easily adjust our font sizes throughout the project.

 

Step 2: Apply clamp()

Now, we apply clamp() to our desired element:

body {
    font-size: clamp(var(--font-min), var(--font-preferred), var(--font-max));
}
Enter fullscreen mode Exit fullscreen mode

With this code, the font size will automatically adjust within the defined range.

 

Step 3: Adjustments and Customization

Feel free to adjust the values of --font-min, --font-max, y --font-preferred to suit your needs. This technique can be applied to any element, not just the font size of the document.

 

Conclusion

And that's it! With a few simple steps, we have created fonts that perfectly adapt to different screen sizes, improving the readability and aesthetics of our websites.


Do you have questions or suggestions? Share what you think in the comments!

Top comments (2)

Collapse
 
danlee1996 profile image
Daniel Lee

Cool article, short and sweet!

Collapse
 
danielpena profile image
Daniel Peña

Como siempre, justo y necesario