Font Size based on Window Width

plasticwrapper.com: playground

The font size of this html tag is directly related to the width of the window. When the page first loads, whatever the original width of the window, this is considered 100%. The font-size for this document is, by default, set to 100%. Therefore, when this window first loads, the font size will be set to 100%.

window.onresize

Now.. when you resize the window, a function is triggered, which in turn calculates the new font-size percentage based on the window's new width.

border widths in em

I gave up on border-widths in em's because they were inconsistent. Technically, each side should have obtained the same border-width dimension. However, depending on the font-size percentage, the width of the border on the top may or may not equal the width of the border on one of the other sides. So, I just switched these units back to "1px" instead. This looks a lot better, I think.

here's the actual javascript

var original_layout_size = 1024; // arbitrary
var root_element = document.getElementsByTagName("html")[0];
var original_window_size = root_element.clientWidth;
var original_font_size = root_element.style.fontSize;
function change_font_size(window_size) {
	var new_font_size = Math.floor(100 * window_size / original_layout_size);
	root_element.style.fontSize = new_font_size + "%";
}

window.onload = function () {
	if (original_window_size != original_layout_size) {
		change_font_size(original_window_size);
	}
};

window.onresize = function () {
	var new_window_size = root_element.clientWidth;
	change_font_size(new_window_size);
};

Of course, in theory, this works great. But, you'll notice that if you keep resizing the window, there are some interesting stylesheet issues that arise... particularly with the line-height of the pre tag which is showing you the script from the header.

Interesting IE6 Behavior

I don't know why, but for some reason, (at least my version of) IE6 gives the best response time for the onresize event handler. IE7 comes in second, and Firefox comes in last. (insert sad face here)

Firefox's onresize == lame

I was hoping that this would look really cool when I drag the window size. Unfortunately, it only looks cool in IE6. Which defies the laws of nature. Nothing looks cool in IE6.

Firefox apparently won't load the onresize event handler until you are finished resizing the window. So, this is really more like an "onresized" handler. The only thing that appears to get Firefox to trigger this event is a change in line wrapping. If, when resizing, the text of a line were to wrap, the event is triggered during the "redraw" of the page.