How to set min-font-size in CSS

I want to set a minimum font size to every element in my HTML page.

For example if there are elements with font-size less then 12px, then they will change to 12px.
But if there are elements with font-size grater then 12px, they will not change.

Is there any way to do it with CSS?


Solution 1:

In CSS3 there is a simple but brilliant hack for that:

font-size:calc(12px + 1.5vw);

This is because the static part of calc() defines the minimum. Even though the dynamic part might shrink to something near 0.

Solution 2:

As of mid-December 2019, the CSS4 min/max-function is exactly what you want:
(tread with care, this is very new, older browsers (aka IE & msEdge) don't support it just yet)
(supported as of Chromium 79 & Firefox v75)

https://developer.mozilla.org/en-US/docs/Web/CSS/min
https://developer.mozilla.org/en-US/docs/Web/CSS/max

Example:

blockquote {
    font-size: max(1em, 12px);
}

That way the font-size will be 1em (if 1em > 12px), but at least 12px.

Unfortunatly this awesome CSS3 feature isn't supported by any browsers yet, but I hope this will change soon!

Edit:

This used to be part of CSS3, but was then re-scheduled for CSS4.
As per December 11th 2019, support arrived in Chrome/Chromium 79 (including on Android, and in Android WebView), and as such also in Microsoft Chredge aka Anaheim including Opera 66 and Safari 11.1 (incl. iOS)

Solution 3:

CSS has a clamp() function that holds the value between the upper and lower bound. The clamp() function enables the selection of the middle value in the range of values between the defined minimum and maximum values.

It simply takes three dimensions:

  1. Minimum value.
  2. List item
  3. Preferred value Maximum allowed value.

try with the code below, and check the window resize, which will change the font size you see in the console. i set maximum value 150px and minimum value 100px.

$(window).resize(function(){
    console.log($('#element').css('font-size'));
});
console.log($('#element').css('font-size'));
h1{
    font-size: 10vw; /* Browsers that do not support "MIN () - MAX ()" and "Clamp ()" functions will take this value.*/
    font-size: max(100px, min(10vw, 150px)); /* Browsers that do not support the "clamp ()" function will take this value. */
    font-size: clamp(100px, 10vw, 150px);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<center>
  <h1 id="element">THIS IS TEXT</h1>
</center>