This time, we’ll explain how to change font sizes according to the browser size in a way that’s easy for beginners to understand.
We’ll use a handy library called jQuery.fontFlex.js. While you could also use CSS media queries, jQuery.fontFlex.js allows for simpler and more intuitive font size adjustments.
CSS Settings for Changing Font Size
First, set up the basic CSS. This CSS sets the default font styles regardless of browser size. Use the code below as a reference (customize as needed).
<style type="text/css">
<!--
body {
font-size: 15px;
font-weight: normal;
line-height: normal;
margin: 5%;
padding: 0;
-webkit-font-smoothing: antialiased;
}
div {
position: fixed;
z-index: 2;
top: calc(50% - 30px);
left: calc(50% - 90px);
width: 180px;
height: 60px;
line-height: 61px;
text-align: center;
border-radius: 60px;
background: #000;
color: #fff;
font-weight: bold;
}
h1 {
font-weight: 300;
line-height: 150%;
color: #777;
}
-->
</style>
JavaScript Settings Using jQuery.fontFlex.js
Next, we’ll use jQuery.fontFlex.js to dynamically change font sizes based on the browser size. First, include the required libraries: jquery.min.js (1.8.0)
and jQuery.fontFlex.js
. Then, apply the fontFlex
method to the target HTML element (in this example, an h1
tag).
Using $(targetTag).fontFlex(min, max, mid)
, you can change the font size for the specified tag depending on the browser size.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript" src="jQuery.fontFlex.js"></script>
<script type="text/javascript">
$(function() {
$('div').delay(1000).fadeOut(800);
$('h1').fontFlex(20,60,40);
});
</script>
HTML Setup
Here, we define the HTML element whose font size we want to change.
In this example, the fontFlex
method is applied to the h1
tag.
<h1><b>jQuery.fontFlex</b> adjusts font size according to the browser size. Try resizing your browser. The font size will change dynamically based on $(targetTag).fontFlex(min, max, mid)
. The jQuery.fontFlex.js file is under 1KB, making it lightweight. Honestly, you could also achieve this with media queries, but using jQuery.fontFlex.js allows for a one-line implementation just by specifying the tag, making it very simple.</h1>
<div>Resize your browser</div>
Demo Page: Adjust Font Size Based on Browser Size with jQuery.fontFlex.js
If you’d like to see it in action, check out the demo page below.
Demo page showing/hiding scrollbars on tall tables
Reference Source: jQuery.fontFlex
For more details on jQuery.fontFlex.js, please refer to the GitHub page below.
Conclusion
By using jQuery.fontFlex.js as introduced in this article, you can easily achieve responsive font sizing without relying on complex CSS media queries. This simple method can be especially helpful for beginners.
※ Please use at your own risk if reusing this code.
Do not reuse the Google Analytics tag from the demo page’s head section.