Dynamically Resizing Text with CSS and Javascript

August 13th, 2008 in Design Tips & Tutorials

by: Matthew Griffin

As the number of screen size and screen resolution possibilities increase, gracefully resizing text becomes more and more important to the usability of websites. I recently worked on a project in which my client wanted to incorporated resizable text into a redesign of an outdated site. In fact, resizable text was the primary directive I received when I was commissioned to work on the project. Their previous website was built in Flash and they had been receiving complaints for several years about how small and unreadable the text was. Meeting their requirements was an exciting new challenge. With a little Javascript and an EM-based layout I was able to meet and exceed their expectations. This article explains how to set up a page for dynamic text resizing and implement a Javascript-powered dynamic text resizing program.

Starting with the Right Framework: The EM-based layout

Using the EM unit as the measurement for your layout instead of pixels, makes for a scalable but sometimes unpredictable website. I recently wrote a tutorial on this subject so I'll just give a brief overview here. The EM is a measurement based on the size the of the current font. Using the EM as your base measurement for columns and list items in your layout allows the entire design to expand or contract as the text size increases or decreases. When you use the EM as your layout measurement, visitors with various font size settings on their browser will all see the same website in the exact same configurations—just smaller or larger.

Using Javascript to Change the Size of Your Text

With Javascript a couple line of code will have your resizing text in no time. To start, create three links on a page. These links will resize the text. Set the href attribute and the onclick to the correct Javascript code like the example below:

<a href="javascript:void(0);" onclick="javascript:body.style.fontSize='1em'">Small Text</a>
<a href="javascript:void(0);" onclick="javascript:body.style.fontSize='2em'">Medium Text</a>
<a href="javascript:void(0);" onclick="javascript:body.style.fontSize='3em'">Large Text</a>

When you click any of the links above, the text in your page will increase or decrease accordingly. The void function call in the href attribute keeps the page from reloading. If you were to leave the href attribute blank (href=""), the page would reload every one of the text resizing links was clicked.

Maintaining the Text Size from Page to Page

Okay, you can find similar examples to the one above all over the internet. The problem is, when you navigate away from the page where the text was changed, the text size goes back to default. This is where cookies come in handy. In case you don't know, cookies are little piece of information you can leave on a visitor's computer so you can recognize them or their preferences next time they come to your site. Here's an example of how to use Javascript to create a cookie that will hold the visitor's text size preference. In this example the cookie will remain valid for thirty days after the visitor leaves the site. If they return within that thirty days, the text size will be the same the last time they visited.

This snippet of Javascript has all the cookie-setting functions you will need to perform the task. Copy this and paste it into the head of your page. Make sure you put it after any stylesheet link so it can override the default text size if necessary:

<script language="javascript" type="text/javascript">
<!--
// JavaScript Document
function set_cookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function get_cookie(name) {
    var name_eq = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(name_eq) == 0) return c.substring(name_eq.length,c.length);
    }
    return null;
}


if(get_cookie("page_size") != null){  
    document.write('<style>');
    document.write('body{');
    document.write('font-size:'+ get_cookie("page_size") + 'em');
    document.write('}');
    document.write('</style>')
}else{
    document.write('<style>');
    document.write('body{');
    document.write('font-size: 1em');
    document.write('}');
    document.write('</style>')  
}
   

-->
</script>

Next, copy and paste these links into the body of the page:

<a href="#" onclick="javascript:body.style.fontSize='1em'; set_cookie('page_size', '1', 30);">Small Text</a>
<a href="#" onclick="javascript:body.style.fontSize='2em'; set_cookie('page_size', '2', 30);">Medium Text</a>
<a href="#" onclick="javascript:body.style.fontSize='3em'; set_cookie('page_size', '3', 30);">Large Text</a>

If you want to see the code in action, check the .

  • 100 Comments
  • 74294 Views

Comments

Posted By: sinan on 08/13/08

thank you for tutarial.

Posted By: Edgar on 08/13/08

Matt, excellent article. short but full of goodies. I had always wondered how sites added that cool effect (small/large). I thought it was so hard. Not so bad after all. Thanks for sharing.

Posted By: Matthew Griffin on 08/13/08

Thanks, Edgar. I hope it comes in handy.

Posted By: Mike on 08/14/08

Very interesting. For the people I work for, and with usability problems I encounter, I'd never thought about font size being a problem. But now that I think about it, some sights have text that is, well, way too small. Thanks for the insight and how to fix.

Posted By: Matthew Grffin on 08/14/08

Thanks, Mike.

Posted By: Stephen Cronin on 08/15/08

I might be missing something here, but I'm not sure why this is necessary. If you're using em based font-sizes, the browser can do the resizing for you, there's no need for extra JavaScript. Why would you need this?

Posted By: Matthew Grffin on 08/15/08

Stephen, the main reason you need an in-page font-size control is that a lot of people don't know that they can increase their font-size with Ctrl++. Also, many people who have poor eyesight keep their font-size at default because increasing it causes a lot of sites to break. The in-page control lets a visitor know that it's safe to make the text bigger.

Posted By: Rodney Schmidt on 08/31/08

I like this method using a cookie and thank you for it.

Posted By: Matthew Grffin on 09/01/08

Thanks, Rodney.

Posted By: Robert Woerheide on 09/17/08

Thanks, Matt. Very clean and simple, especially compared to the other text re-sizing scripts floating around the web. Any way to have this apply to specific div/span classes and ids in addition body text? I will play around with this but thank you in advance for any advice.

Posted By: Carol on 10/17/08

is there any way of reducing the size of the text, obviously not too small as that defeats the object, just slightly, from what ive tried i cant figure it out? Thanks

Posted By: Tim on 12/26/08

The if/else code in the head section is to set the body element font size during a page reload, I take it? So I'm curious as to why you're using document.write to build style code when you're using body.style.fontSize to set the font via the onclick method. I'm having a problem with my code: I'm using the fontSize property for both a function call and for page reload, and what happens is that when I call the function, the new size is set momentarily and then the page reverts to the previous font size.

Posted By: Matthew Grffin on 12/29/08

Tim, I think the answer you are looking for is in the article. Just read a little more carefully. The issue you're describing is exactly the issue that this tutorial addresses.

Posted By: Ken on 12/30/08

For some reason my font size is not working. It is just making the left size large and not any of the text on the homepage. Can you take a look at the code and let me know why? Maybe I did something wrong. This has been a rough week for me. Thanks

Posted By: Ken on 12/30/08

This Ken again. I only put the code on one html page for testing. When you link to the homepage, click on left side menu for "seniormissionpartners". On seniormissionpartners, click on "testsize" and there you can look at the code. Thanks

Posted By: Matthew Grffin on 12/30/08

Ken, I don't normally do this but I took a quick look at your code. It looks like your text size links are calling a javascript function called createCookie but I don't see this function listed anywhere in your code. I think you're just calling a nonexistent function. Follow the example above and you should be able to get it.

Posted By: Ken on 12/30/08

Thanks for looking at this for me. I tried putting the code in one of the html pages to see if it works. For some reason it is pushing everything down to the bottom and not making the text larger. I really hate to bug you but I just can't seem to get this to work. If I can on one of the html pages then I can with the rest. Can you look at this page for me? If I don't get this to work, there is no way I can have a super New Years. I will have to work to figure this out. That html page is on seniormissionpartners, click on "testsize" and there you can look at the code. By the way, I like your Bible versions. I to am a christan and been praying that the Lord would open my eyes? I don't normally give out my number but here it is. I need the help so much that, why not. 770-630-8655 Ken

Posted By: Matthew Grffin on 12/31/08

Ken, the best advice I can give you is to go to the example page provided in the article above and copy the code directly into your page. Then make incremental changes to fit it to your design. Everything should work that way. That's the best I can do for you. We all have struggles with code like you're having. You just have to stick with it.

Posted By: Ken on 01/05/09

It is working now. I have made some changes. Thanks, Ken

Posted By: Garry on 02/13/09

Would you be able to include 2 versions of this in the same document and have one for background colour as well as the original for text size? This works brilliant by the way, cheers.

Posted By: Matthew Grffin on 02/13/09

@Gary - I assume you are wanting to change the background color dynamically too? If so, the answer is absolutely.

Posted By: Jon on 04/14/09

Thanks for an excellent piece of code - particularly the cookie ;) my problem is tho, i cant get it to work with frames, it will resize the navigation frame (where i placed the increase/decrease code) but not the body text :(

Posted By: diana on 05/19/09

I came across your site no to long ago I am new to web designing I figured it would be something easy that I can learn in a couple of days but I was wrong. All you wed designers out there you guys have a tough job. Any ways I inserted the code and it worked but I have to remove this code in order for it work :(<link rel="stylesheet" href="css/mm_finance.css" type="text/css" />). When I do remove it my site looks horrible is there a way I can make it work but keeping my page looking pretty. Thanks

Posted By: Matthew Griffin on 05/19/09

Diana, put that code back in. Then open the mm_finance.css file and remove any font-size attributes from the "body" selector. It's usually right up at the top. I'm pretty sure that will solve your problem.

Posted By: Diana on 05/20/09

Matt, Thank you so very much for the help it worked. Know I can go back and fix little details that are missing. Thanks a bunches,really appreciate it.

Posted By: Diana on 05/20/09

hi Matt its me again i put the code into 2 of the pages, but everytime i click on either of the 2 pages the text size doesn't follow.

Posted By: Sandy on 08/11/09

What is the reason for changing href="javascript:void(0);" to href="#" when using cookies?

Posted By: Matthew Grffin on 08/11/09

Sandy, it's been awhile since I dealt with this script but I do remember that something funky happens when you leave the # in the href property. It has to do with how most browsers handle links that activate both javascript functions and hyperlinks at the same time.

Posted By: Teen Pregnant on 09/22/09

Hello, I like this method using a cookie .

Posted By: Breast Cancer Awareness on 09/22/09

Great post thanks for sharing a informative

Posted By: Generic Viagra on 09/29/09

I feel very good blog with lots of variety, keep like that.

Posted By: GS on 10/28/09

Thank you, I just tried the code, it works very well. Even after a wonderful job, I have a one request. I wanted to setup resizing for multiple times. Example just clicking on Large text twice make the text grow 2 time larger. This method is more user friendly. Is this possible?

Posted By: GS on 10/28/09

I forgot to mention, if it is not too much trouble can you please email me , with your next post. Thank you,

Posted By: Matthew Griffin on 10/28/09

Yes, GS, you can definitely do this. All you will need to do is rearrange the code a little bit. I'm not going take the time to write all the code for you but essentially what you would do is set a global variable at the beginning of your javascript that holds the value of the font size on the page. Then, when your button is clicked, a function would be called that would do exactly what the "onclick" in the example does except it would add 1 to the universal variable and use that number as the new font size. Hope that helps.

Posted By: Rach on 11/09/09

I'm building a site at the moment and this bit of code was just what I was looking for - great! However, for some reason, if I make the textlarger then click refresh - it goes massive! Any idea what the problem could be? Many thanks for posting this.

Posted By: Matthew Griffin on 11/09/09

Rach, I checked out your site in Chrome and IE and it worked just fine. It may just be a cache issue.

Posted By: Scott on 02/13/10

Is there a way to modify the code to only affect a particular DIV instead of the entire body? Thanks for creating this code for others to use. It works great. I just don't want to change the entire BODY. Thanks again, Scott

Posted By: vithya on 02/18/10

Is there a way to modify the code to only affect a <p> tag instead of the entire body.Because i dont want to chanhge the size for whole body Thanks scott

Posted By: vithya on 02/18/10

Hi Matt your code was really usefull but i dont want to increase the size for entire body text but only paragraph tag can anyone tell me how to do that:(

Post Your Comment

Comments are closed.