Home > front end >  CSS clamp() formula for font-size
CSS clamp() formula for font-size

Time:10-18

I'm trying to understand how this tool figures out the 2nd parameter for the clamp() function: https://fluid-typography.netlify.app/. Is anyone able to explain that part?

I understand the 1st and 3rd parameters as they are pretty self-explanatory. It's the 2nd parameter that's confusing.

Minimum size 1.5rem at a viewport width of 700px.

Maximum size 3rem at a viewport width of 1000px.

font-size: clamp(1.5rem, 8vw - 2rem, 3rem);

CodePudding user response:

font-size: clamp(1.5rem, 8vw - 2rem, 3rem);

As you say, the first and third parameters are fairly simple, as they both just use the rem unit. But the middle parameter is the result of a calculation, finding the difference between two values with different units.

8vw means 8% of the viewport width. 2rem means twice the font size of the root element. So, 8vw - 2rem means 8% of the viewport minus twice the font size of the root element. Because values in rem will stay the same (barring any @media directives in CSS changing the font size of the root element), but vw units scale with the size of the viewport, this means the result of that middle parameter will scale with the size of the viewport.

It's the 8vw part that's important, since that's the part that scales with viewport width. The - 2rem part of that middle parameter is really just an offset to get things looking as desired at any particular viewport.

When used with clamp(), the resulting value will never be smaller than 1.5rem, and it will never be larger than 3rem, but aside from those restrictions it will be 8vw - 2rem whenever it can.

CodePudding user response:

The formula is font-size = Xvw - Yrem. At 700px of viewport (100vw = 700px so 1vw = 7px) we want 1.5rem (1.5rem = 24px) and at 1000px (100vw = 1000px so 1vw = 10px) we want 3rem (3rem = 48px) so:

24px = X*7px  - Y*16px
48px = X*10px - Y*16px

Solve the equation and you will get X = 8 and Y = 2

You have a linear function to define the font-size between 700px and 1000px. Outside of this range we want the font-size to be fixed that's why we use clamp() to have a min and max value

  •  Tags:  
  • css
  • Related