Search code examples
cssmedia-queriesclamp

CSS Clamp with fixed value when between min and max viewport


Is it possible to set a fixed value inside a css clamp so that instead of a font size scaling between a minimum viewport width and a maximum it is the middle size between the min and the max whilst between those two breakpoints.

This can obviously be done with media queries but in the interest of reducing the amount of code I wondered if it could be done with clamp.

Min viewport 680px; Max Viewport 1020px;

clamp(20px, -- 28px when > min viewport && < max viewport -- , 40px); 

Solution

  • It's possible by nesting clamp() but not intuitive

    h1 {
      /* first breakpoint*/
      --w1: 1020px;
      /* second breakpoint*/
      --w2: 680px;
      
      font-size:
        clamp(clamp(                20px,  /* < w2 */
           (100vw - var(--w2))*1000,28px), /* > w2 && < w1 */
           (100vw - var(--w1))*1000,40px); /* > w1 */
    }
    <h1>a title</h1>

    I am using a similar technique in this article if you want more detail: https://css-tricks.com/responsive-layouts-fewer-media-queries/