Search code examples
htmlcsstypography

Fluid Typography


I'm trying to use fluid typography and the goal is to scale the text between screen sizes 300px and 1160px.

So at 1160px I want 56px H1 and mobile 30px.

The problem I'm having is the H1 increases in size past the 1160px and keeps increasing.

h1 {
  font-size: calc(30px + (56 - 30) * ((100vw - 300px) / (1160 - 300)));
}
<H1>Fluid Typography</H1>


Solution

  • You need to limit fluid calculation of h1 between media queries. Try this:

    h1 { font-size: 30px; }
    
    @media (min-width: 300px) { 
      h1 {
        font-size: calc(30px + (56 - 30) * ((100vw - 300px) / (1160 - 300)));    
      }
    }
    
    @media (min-width: 1160px) { 
      h1 {
        font-size: 56px; 
      }
    }
    

    First, the minimum font-size needs to be provided: that's the first line. Then between two breakpoints you introduce fluid calculation which, at 300px gives exactly 30px of font-size, and again at 1160px calculates to exactly 56px. After 1160px you keep it at 56px again using media query. This way you have a graceful transition between static and fluid typography between the set breakpoints.

    You can find more examples of this here: https://www.madebymike.com.au/writing/fluid-type-calc-examples/ or here: https://www.smashingmagazine.com/2016/05/fluid-typography/

    Let me know if you need more examples, I've done a lot of these.