'How to implement max-font-size?

I want to specify my font size using vw, as in

font-size: 3vw;

However, I also want to limit the font size to say 36px. How can I achieve the equivalent of max-font-size, which does not exist--is the only option to use media queries?



Solution 1:[1]

Here is another idea. The calc function uses double precision float. Therefore it exhibits a step function near 1e18. For example,

width: calc(6e18px + 100vw - 6e18px);

This will snap to values 0px, 1024px, 2048px, etc. see pen https://codepen.io/jdhenckel/pen/bQNgyW

The step function can be used to create abs value and min/max with some clever maths. For instance

max(x, y) = x - (x + y) * step(y - x)

Given step(z) is zero when z<0 and one otherwise.

just an idea, not very practical, but maybe fun to try.


(Caution: this technique depends on an implementation detail that is not in any specification; currently, it works in Chrome and Safari, but not in Firefox, Edge or Internet Explorer, which don’t use double-precision floats for CSS values.)


UPDATE: this post is no longer useful (was it ever?) since CSS now supports min, max, and clamp.

Solution 2:[2]

Another way increases font size slowly, this will not limit max font size, but even on very wide screens, it will look better. Does not answer question in perfect way, but its 1 line...

font-size: calc(16px + 1vw);

Update: CSS improved and i recommend using clamp(min, preferred, max) function:

font-size: clamp(12px, 2vw, 20px);

Solution 3:[3]

At some point, the font-size exceeds the 36px scale right, find that. Assuming, it exceeds when the width: 2048px:

@media screen and (min-width: 2048px) {
  .selector {
     font-size: 36px;
  }
}

Yes, unfortunately you need to use the @media queries. I hope that doesn't affect anything.

Solution 4:[4]

According to this website (there are ads in this site), If you don't want to use clamp():

font-size: 24px;  

font-size: min(max(3.5vw, 16px), 40px);

Line one for IE.
Line two for others, means font-size:3.5vw, max-font-size:40px, min-font-size:16px.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Praveen Kumar Purushothaman
Solution 4 c j