Web development and Tech news Blog site. WEBISFREE.com

HOME > css

[CSS] Is there a way to set the maximum value of font size? If not, what's the alternative?

Last Modified : 17 Oct, 2023 / Created : 17 Oct, 2023
226
View Count


Hello! It's WebIsFree 😊

"One of the thoughts that comes to mind when using font size in responsive design is..."


While building responsive and mobile websites with CSS, I think it would be convenient to set a maximum font size. What if there's a property we could use directly, like max-font-size?



There's no way to set the maximum font size...
To conclude, there's no such property. However, there are ways to implement something similar. The following methods, including those that use JavaScript, exist:


1. Using JavaScript
It's possible to check the font size of a specific element using JavaScript. If that size exceeds the desired maximum, you can reduce it. For instance, you can retrieve the size of the text in the HTML below and if it exceeds a specific value, set it to a maximum. The CSS would be as follows:
<div id="textDiv">This is some text.</div>

You can determine the font value of the text element #textDiv from the above HTML and set it as follows. Here's an example where the maximum value is 24px:
var div = document.getElementById('textDiv');
var computedStyle = window.getComputedStyle(div);
var fontSize = parseFloat(computedStyle.fontSize);

if (fontSize > 24) { // if the computed font size is greater than 24px
  div.style.fontSize = '24px'; // set it to 24px
}


2. Using the css clamp() function
This method uses the css clamp() function to set a value. Personally, I prefer this method over the previous one because it doesn't require scripting and can be set with just CSS. It's especially useful in responsive sites because it adjusts the size dynamically.

A simple example of using clamp() is:
.my-text {
font-size: clamp(10px, 4vw, 30px);
}


The above code sets the font size to a minimum of 10px and a maximum of 30px. The value between the two is adjusted based on 4% of the set viewport width. If used properly, clamp() is very useful. It's briefly set up as clamp(minimum value, preferred value, maximum value).

clamp(minimum value, preferred value, maximum value)

This means that you have the advantage of specifying a range for minimum and maximum values.


3. Using media queries
This method is also possible with just CSS. If you want to specify a different font size based on screen size, but want to set it to a maximum or minimum value at a certain screen size, you can use media queries.
.my-text {
  font-size: 3vw;
}

@media screen and (max-width: 1024px) {
  .my-text {
    font-size: 12px;
  }
}

The above example is used to set the font size to a minimum of 12px when the screen width is less than 1024px.


We've briefly looked at how to use the maximum or minimum values of fonts.
Perhaps you're looking for the following text as well?

    Previous

    Exploring the CSS will-change Style Property