Power Your Software Testing with AI Agents and Cloud

The Native AI-Agentic Cloud Platform to Supercharge Quality Engineering. Test Intelligently and Ship Faster.

Web DevelopmentTutorial

Fluid Typography With CSS Clamp: A Complete Guide

Learn how the CSS clamp() function sets fluid font sizes that scale with the viewport, with worked examples, min and max comparisons, and zoom safe limits.

Last Updated on:

Fluid typography with CSS clamp scales font size with the viewport between a fixed minimum and a fixed maximum.

The clamp() function takes three arguments, a minimum, a preferred value and a maximum, and it stays fluid only when the preferred value uses a viewport unit such as 5vw.

This guide covers typography basics, fluid typography with media queries and calc(), the CSS clamp method, how to calculate the preferred value, how min() and max() compare with clamp(), and whether AI coding assistants write correct clamp declarations.

Key Takeaways

  • Fluid typography scales font size with the viewport, so text stays readable on a phone and a desktop monitor without the reader zooming in.
  • CSS media queries and the calc() function can both deliver fluid type, but each one asks the developer to work out breakpoints or a font size formula by hand.
  • The CSS clamp() function takes a minimum, a preferred value and a maximum, and falls back to whichever bound the preferred value crosses.
  • A clamp() declaration is fluid only when the preferred value is viewport based, such as clamp(16px, 5vw, 50px), because a fixed middle value like 40px never changes.
  • MDN recommends a maximum at least twice the minimum when relative units are used, which keeps text growing to 200 percent browser zoom and satisfies WCAG Success Criterion 1.4.4 Resize Text.
  • The CSS min() and max() functions leave one end of the range unbounded, so clamp() is the safer function for font sizes and container widths.

Typography Basics

Before jumping straight to the responsive design, I believe a brief introduction to typography is important for readers who are not familiar with it. For expert professionals and designers who have already dealt with typography can skip to the fluid typography section.

Typography is the careful selection of colour, contrast, size, font, alignment, and other factors that directly affect the design of type on a web page. Typography is a thoughtful process and needs in depth analysis of each element described above and being used on the web page.

As a beginner, the thumb rule of typography based on my experience is, never think that if you can read it, everyone can or if you feel comfortable with the text properties, everybody does.

Typography has a different effect on everyone. Some people are fast readers, some people are sensitive to certain colours etc. This post is not about typography and therefore we shall not go too deep into this, though the typography tips that change the way you design mobile web cover it in more depth. But to make you understand, let's just brush up on just two properties in short: contrast and font.

Contrast

In laymen terms, contrast on a web page (focusing on typography) can be understood as to how different the text colour and its background are.

Contrast

Here I have designed a small web page with three different contrasts. Which one is easier to read for you? The first block has a contrast ratio of 1.53 which is extremely poor in terms of WCAG guidelines.

The second block passes the AAA level of the guidelines (which is the best level) to read and the third block is the most common in web design and arguably the best one too. You can calculate the contrast ratio with online tools such as contrast-ratio. Contrast ratio is an essential part of accessibility and for a better user experience, it should pass the WCAG Level AA. Good typography consists of a perfect contrast that is comfortable for everyone.

Font

The next thing to take care of in typography is the font we use on the web page. The font has two main segments: the size and the type of font. Let's first see the type of font.

There are two types of fonts available that can be implemented in modern web design.

Font

And the difference between them is this:

difference

The Serif fonts have these pointed end strokes while the "Sans-Serif" does not (tip to remember: sans means without in English). These two types of fonts can dramatically change the impact your content will have on the reader.

Serif fonts are hard to read because of the pointy ends. But this claim is only satisfied when we are talking about normal small text (12-14px) and letter spacing is normal. As we increase the font size, serif fonts do not create any trouble and can be read quite comfortably.

In fact, in bigger headings and banner images, serif fonts do look good. On the downside, if you choose to use serif and increase the normal body font size, it will take much more space on the web page which is not a good sign.

Hence, it's good to always experiment with the typography on your web page and take feedback from users.

Key Takeaway: Readable typography starts with a text and background contrast that passes WCAG Level AA and a font type chosen for its size, because serif faces are harder to read at normal body sizes of 12px to 14px.

Fluid Typography - The Responsiveness of Fonts

Fluid typography makes the typography responsive so that when we change the screen size, the font size, font height, space and other type attributes all change with respect to it.

Let's test the above example of contrast colour using LT Browser, a developer-friendly browser that helps you test websites for responsiveness instantly across 50+ screen resolutions. You can even create custom screen resolutions, debug with inbuilt dev tools, collaborate with team members by sharing screenshots or videos and even run a performance test report.

If I render the same website on a mobile device, I get this:

Fluid Typographydownload browser

Honestly, if I were the user and saw this type of content, I would press the back button to navigate to any other link. No matter how much focus you have put up on the typography, all the hard work is down the drain if it is not fluid in nature.

Fluid typography is a short concept but of utmost importance, just like the selectors listed in any CSS selectors cheat sheet. Going forward we will see two methods to apply fluid typography on a web page. One with CSS media queries and the other with an in-built CSS clamp function.

Test across 3000+ browser and OS environments with TestMu AI

Fluid Typography with CSS Media Queries

Before continuing to this section about fluid typography with CSS media queries, it is highly recommended to have prior knowledge of media queries used in CSS. You can take help from your favourite CSS source or the post I wrote on CSS Media Queries and implementing them to achieve responsiveness.

In short, media queries detect the media device on which the website is rendered and applies the defined media rules to the selector used. For example:

@media screen and (max-width: 840px){
  p {
     color: red;
}
}

The above media query makes the content inside the "p" tag red on a "screen" whose maximum width is 840px.

Fluid typography also requires similar treatment. We are looking to change the type properties according to the viewport of the device and when we talk about viewport in typography, the first thing that comes to mind is "vw"? Can we give "vw' a try here?

Fluid Typography - Fixed and Static

With fixed values in our media queries, we can define a rule to change the font size according to the current viewport of the device. Defining the font size in "vw" gives us the advantage to skip the calculation and just rely on CSS to adjust the font according to the viewport. "VW" works with reference to the viewport device. A font size of 2vw is 2% of the current viewport. For example, if the viewport is of 1000px, 2vw would correspond to 1000 * 2% = 20px.

p{
font-size: 2vw;
}
LambdaTest live browser preview

The only problem with fixed value as demonstrated is it works fine only for a given range of resolutions. If the resolution becomes too big, the font would become too big and often it is not required.

You can observe a similar pattern when the resolution is too low. Practically, font size can be utilized to a range of viewports rather than always moving it upside down. Apart from the "vw" unit, you can use other options too in place of vw (viewport width):

vh: viewport height.

vmin: takes the smaller value of viewport height and width.

vmax: takes the larger value of the viewport.

Therefore, we can use media queries here to implement the adjustments only when it is required. The breakpoints can be found out by simple math that we applied in the previous example where:

value * resolution = font size

Here, we want the breakpoint resolution with a fixed value of font size that we know. So, if I want to know the breakpoint of 20px that we used above, we change the position of variables as follows:

value / font size * 100 = resolution - Eq. 1

Substituting the values:

20/2 * 100 = 1000px - Eq. 2

Or 10px for 500 resolution etc. Finding the breakpoint is very important. If you put down any value as you wish the font size would jump after the "min-width" which is not a very "fluid" design. We can now apply media queries because I don't want my font size to go below 10px ever and beyond 16px which brings out a resolution of 800px (using the equations).

@media (min-width:500px){
font-size : 2vw;
}

@media (min-width: 800px){
font-size: 16px;
}

Results:

Fluid typography browser demo

This method to implement the fluid typography is a little hectic though. With all the calculations and hit and try methods, it becomes too much of a burden when we have more than three or four elements on our web applications.

Fluid Typography with Calc Function

We can make a small adjustment to our above code and leave out the calculation part to the CSS itself by using the calc function. This option is great when you don't want to bug yourself with calculations and want fluid typography that does not jump from a small font to bigger ones instantaneously.

The calc function is used to calculate an expression when specified inside the CSS property values. Any property that takes length, percentage, number, time, integer, angle and time can be specified as an operator in calc.

Calc takes four types of operands: addition, subtraction, multiplication and division. An important and probably the only thing to remember while constructing a "calc" function is that the operators "+" and "-" should always be surrounded by white space. If the operand and the operator are as follows:

calc(15vw -35vw)

It will be considered as -35 and the expression will become invalid. By defining a mathematical expression inside the calc function, we can quickly achieve fluid typography (or at least easier than the previous method).

The following expression is a tested expression for the font size and will work by calculating the font size within a range of numbers.

font-size: calc([minimum_font_size] + ([maximum_font_size - minimum_font_size]) * ((100vw - [minimum_viewport]) / ([maximum_viewport - minimum_viewport])));

To substitute random values just for the demonstration, the calc function will become as follows:

p {
font-size: calc(16 + ([16 - 12]) * ((100vw - 1200) / (1200 - 500)));
}

100 has been used because of the percentage terms. Please refer to equation 1 and equation 2 to know more about it.

With calc function in our hand, we don't need to worry about those absurd jerks in fluidity and extra head of calculations. It is better than the first method but still a bit more "mathematical" than our next method.

Key Takeaway: Fluid typography can be built with CSS media queries or the calc() function, but media queries need every breakpoint calculated by hand and calc() needs a font size formula written out in full.

Fluid Typography with CSS Clamp Method

Our final method to achieve fluid typography is the CSS clamp method. Seeing how web developers were involved in tedious process of calculating their font size for every element that displays font to achieve fluid typography, the clamp function was introduced in CSS Level 4 to ease out their pain.

The Clamp function works as one of the bounds in CSS, the other two being the "max" and "min" functions.

The CSS Clamp function takes two bounds and a preferred value. These bounds are the minimum bound and the maximum bound. The function roams around these bounds and selects a value from in between them. If the preferred value goes below the minimum bound, the minimum bound is used. On the other side, when it goes beyond the maximum bound, the maximum bound is used.

Consider the following example of the CSS Clamp function:

<style>
      p{
        font-size: clamp(12px, 40px , 200px);
        margin-top: 40px;
        text-align: center;
}
    </style>

The font size of the paragraph is returned as 40 on the loaded page (the middle value aka the preferred value). This is the problem here. When the preferred value is in between the min and max, it will always be the preferred value that is returned even if the viewport width goes below 200px. With such an arrangement, fluid typography will not be achieved as the font size will remain static. It's like defining a font size conventionally in simple px terms.

Therefore, it is better to use an expression in the place that returns this value based on the device's viewport so that as the viewport changes, the font size of the element changes too! We can take advantage of the clamp function that monitors the preferred value to always be within the bounds.

In the following example, I am considering a 50% expression as a preferred value restricted between ridiculously small 12px and 200px for an image width:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <style>
      img {
        width: clamp(12px, 210px, 200px);
        margin-top: 40px;
        text-align: center;
}
    </style>
  </head>
  <body>
      <div>
    <img src="cat.jpg" id="mycat">

    </body>
</html>
Element width inspector overlay

So, here we get restricted by the maximum bound because the viewport 50% was greater than 200.

Apart from an expression as simple as used above, you can also use a complete calc function equipped with expressions in the preferred value. Or you can go ahead with a single base value along with the percentage as demonstrated above in the following approach:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <style>
      p {
        font-size: clamp(16px, 5vw, 50px);
        
        text-align: center;
}
    </style>


  </head>
  <body>
      <div>
  <p id = "paragraph">Your Text.</p>
  <br><br>
    </body>
</html>
CSS clamp fluid typography

The fluid typography is achieved by this small function that was much needed for the web developers. The CSS Clamp function can be used for a whole lot of use cases but using it for font sizes or fluid typography is a classical and most popular use case. You can experiment with the function in a CodePen and watch the rendered font size settle on each bound as you drag the viewport.

Choose the two bounds with browser zoom in mind. If the maximum sits close to the minimum, the text stops growing before a reader reaches 200 percent zoom, and the page then fails WCAG Success Criterion 1.4.4 Resize Text. MDN recommends a maximum that is at least twice the minimum when you use relative units, so font-size: clamp(1rem, 2.5vw, 2rem) is a safer starting point than two bounds a few pixels apart. Adding a rem term to the preferred value, as in font-size: clamp(1rem, 1rem + 1.5vw, 2rem), keeps the reader's own base font size inside the calculation instead of letting the viewport decide everything.

The preferred value does not have to read from the viewport. Container query length units let type scale against the element's own container, which matters when the same card renders in a wide main column on one page and a narrow sidebar on another. Declare container-type: inline-size on the wrapper, then size the child with font-size: clamp(1rem, 1rem + 1cqi, 2rem), where 1cqi equals one percent of the container inline size. MDN records container queries as Baseline widely available across browsers since February 2023, so the pattern is safe in production.

MDN records clamp() as Baseline widely available across browsers since July 2020. You can use it in production without worrying about cross browser compatibility issues.

Internet Explorer never supported clamp(), and Microsoft has since retired that browser, so the death of IE leaves no fallback to write.

Key Takeaway: The CSS clamp() function produces fluid text only when its preferred value is an expression such as 5vw, because a fixed preferred value like 40px is returned unchanged at every viewport width.

How Do You Calculate the Preferred Value in CSS Clamp?

Pick two points and solve for the straight line between them. Set a minimum font size at a minimum viewport width and a maximum font size at a maximum viewport width, then express that line as a rem term plus a vw term. Smashing Magazine sets out the two formulas. The viewport coefficient is 100 * (y2 - y1) / (x2 - x1) and the intercept is (x1 * y2 - x2 * y1) / (x1 - x2), where y1 and y2 are the two font sizes and x1 and x2 are the two viewport widths.

Work an example. Ask for 16px at a 320px viewport and 24px at a 1280px viewport. The coefficient comes out as 100 * (24 - 16) / (1280 - 320), which is 0.8333vw. The intercept comes out as (320 * 24 - 1280 * 16) / (320 - 1280), which is 13.333px, or 0.8333rem when the root font size is 16px. The declaration is font-size: clamp(1rem, 0.8333rem + 0.8333vw, 1.5rem). Substitute each viewport width back into the expression and you should get the font size you asked for, which is how you check the two numbers before you ship them.

Calculators run this arithmetic across a whole scale instead of one declaration. The Utopia type scale calculator takes the two viewport widths, the two font sizes and a ratio, then returns one custom property per step in the form --step-0: clamp(1.125rem, 1.0739rem + 0.2273vw, 1.25rem). Its space calculator applies the same method to margin, padding and gap, so the whitespace around a heading scales on the same line the heading does. Keep the rem term in the expression either way. Strip it and leave a bare vw value, and the text stops answering to the reader's own font size setting.

Key Takeaway: The preferred value in a CSS clamp() declaration is the straight line through two chosen points, so asking for 16px at a 320px viewport and 24px at a 1280px viewport gives font-size: clamp(1rem, 0.8333rem + 0.8333vw, 1.5rem).

Min Max and Clamp Function in CSS

Often, you would see people using just the "max" function or just the "min" function to achieve almost the same results of fluid typography that we tried above. They do work a bit like each other, and when we want to take control over a container width or fluid typography, often we can get confused between the three. Therefore, a small section demonstrating the min and max function is necessary when we talk about CSS Clamp.

Min Function in CSS

The "min" function in CSS takes different values as arguments (similar to clamp) and applies the value that is the minimum of all of them.

The following code is demonstrated later with the video:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <style>
      div {
        width: min(50vw, 500px);
        text-align: center;
}
    </style>
<script>
   function calcwidth(){
     setInterval(function(){var x = document.getElementById("divblock").clientWidth;
     document.getElementById('mywidth').innerHTML = x;}, 100);
  }
</script>
  </head>
   <body onload="calcwidth()" style= "background-color: rgb(181, 209, 255)">
      <div style="display: block" id="divblock">
   <h2> My Width is <span id="mywidth"></span></h2>
  <br><br>
</div>
    </body>
</html>
CSS min function demo

So, the width of my "div" box remains constant at 500px because it is the minimum value compared to 50vw. But, as soon as 50vw becomes less than 500px, the width of the "div" box starts to change too.

Max Function in CSS

Once you have dealt with the min function above, decoding what max function would do is not rocket science. The max function works as just the converse of the min function where the maximum of the values is chosen instead of the minimum.

Change just a single line (Line Number 8 as per count) by changing the word "min" to "max".

width: max(50vw, 500px);
Max Function in CSS

The width gets fixed at 500px as soon as the 50vw becomes lesser than it.

The min() and max() functions carry the same Baseline widely available status as clamp(), across browsers since July 2020.

Min and max functions are great and are very essential in certain use cases. But, they both provide one loose end from their side. You cannot judge how small the font size or width would go when you use the min function or how large it would get with the max function. A precautionary function that works smoothly here is the clamp function and therefore as far as accessibility is concerned, the min and max functions should be avoided.

Also, if you ponder over the min and max functions a bit, you will realise that the clamp function is actually made up of these functions as this snippet:

width: clamp(150px, 50%, 1000px);   =   width: max(150px, min(50%, 1000px));

But using Clamp is clean and understandable.

The formal syntax for clamp() also accepts the keyword none in either bound, which removes the clamp on that side. clamp(1rem, 2.5vw, none) behaves like max(1rem, 2.5vw), and clamp(none, 50%, 400px) behaves like min(50%, 400px). Check browser support for the keyword before you rely on it.

Key Takeaway: The CSS min() and max() functions leave one end of the range unbounded, so clamp(), which behaves like max(minimum, min(preferred, maximum)), is the safer function for sizing text.

Can AI Coding Assistants Write a Correct CSS Clamp Declaration?

They produce valid syntax, and the arithmetic still needs checking. The clamp() function takes three arguments in a fixed order, so an assistant asked for fluid type returns a usable one liner in seconds. What the model cannot confirm is whether the preferred value actually passes through the two points you asked for. Substitute both viewport widths back into the expression, the way the worked example above does, before the declaration goes into a stylesheet.

Chrome DevTools ships an AI assistance panel that puts Gemini inside DevTools. Select an element, ask why its computed font size is what it is, and the panel explains the cascade and proposes CSS changes. Google documents the feature as experimental and disabled by default, limited to signed in users who are at least 18 and in a supported location, and its own note says the feature may generate inaccurate or offensive information that does not represent Google's views. Read a clamp() suggestion from it as a draft.

The failure that shows up most often in generated CSS is a bare viewport preferred value. A line such as font-size: clamp(1rem, 2vw, 2rem) has relative bounds but no rem term in the middle, so the text stops answering to the reader's own base font size. Keep a rem term in the preferred value and keep the maximum at least twice the minimum, or the page can fail WCAG Success Criterion 1.4.4 Resize Text once a reader reaches 200 percent zoom. Generating the declaration is the fast part. Rendering it at 320px, at 1280px and at 200 percent zoom is the part that still has to be run.

Key Takeaway: An AI assistant can produce a syntactically valid clamp() declaration in seconds, but the two endpoint font sizes and the rem term in the preferred value still have to be checked by rendering the page.

Conclusion

Over the years, we have seen a massive surge in mobile device usage. This gave birth to the term fluid typography, which makes web page typography immune to changing viewports. Font size also plays a very crucial role in creating an impact for the user of your website. People hardly zoom in to read the content. They take the easiest shortcut; the back button. One such function that takes control over deciding what font size to put is the CSS Clamp function. As explained in the post, the clamp function is better and much more helpful than the min and max function, even though it is a mix of them behind the scenes.

Furthermore, you can also test whether implementing the CSS clamp function is working across different browsers and browser versions using a cloud testing platform like TestMu AI that enables you to perform browser compatibility testing at scale. I hope this post increased your knowledge on CSS Clamp and fluid typography and the next time you are developing a website, make sure you implement this fluid typography using the CSS Clamp function.

Run tests up to 70% faster on the TestMu AI cloud grid

Author

...

Harish Rajora

Blogs: 97

  • Twitter
  • Linkedin

Harish Rajora is a software developer at TestMu AI with over 6 years of hands-on experience in Python and cross-platform application development across Windows, macOS, and Linux. He has authored 800+ technical articles and worked on large-scale projects, including GenAI applications and core engineering features used by millions. Harish has led DevOps initiatives building CI/CD pipelines with Jenkins, AWS, GitLab, and GitHub, and holds an M.Tech in Software Engineering from IIIT Allahabad.

Add to Google preferred sources

Summarise with AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free

CSS Clamp Fluid Typography FAQs

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests