Dynamically Changing CSS Based on Browser Width

The content in this paragraph tag with id="mytag" will be changed according to the width of the browser window. In this example, this paragraph will go no smaller than 600 pixels and no wider than 900 pixels. If the browser width is in between 600 and 900, then this paragraph will resize to 100%.

What is this code doing?

If you resize your browser window, you can see that the light blue paragraph tag above will change color and resize itself differently depending on the width of the browser window. NOTE: IE doesn't work properly when decreasing the size of the browser window. However, it will set the layout properly based on the window size when the page loads and/or reloads.

How does it work?

There is a small bit of javascript that you include on your page. This javascript will handle the window.onresize event and change the className property of an element called 'resize_css'. The className will be set to narrow, medium or wide depending on the width of the browser window. Any tags within the resize_css div can be styled differently for each width using normal CSS syntax like so:

.narrow #mytag {background-color: #eeeeff; width: 600px;}
.medium #mytag {background-color: #bbbbff; width: 100%;}
.wide #mytag {background-color: #9999ff; width: 900px}

Why would I want to do this?

The above example isn't particularly exciting, however this is a basic example for demo purposes only. A more interesting use might be to change your layout from three columns to two columns if the window is less than a certain width. Or, you might have a liquid layout that changes to fixed width if the browser window is extremly wide.