views:

171

answers:

1

I have many elements positioned absolutely in my page. What is the best practice method to re-adjust its position on window resize(all of them)?

+2  A: 

I'd suggest the best practise is to do this with CSS and avoid doing it with JavaScript if you possibly can. So avoid absolute positioning when you can, and when positioning absolutely use percentages rather than pixel values where possible, use right rather than left when positioning elements you want anchored right, use bottom rather than top when positioning elements you want anchored to the bottom, etc., etc. E.g.: Let the browser handle it for you.

Example:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Resize Demo Page</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
#anchorRight {
    position: absolute;
    right: 0px;
    top: 20%;
    border: 1px solid black;
}
#anchorBottom {
    position: absolute;
    bottom: 0px;
    left:  20%;
    border: 1px solid black;
}
#anchorBoth {
    position: absolute;
    right: 0px;
    bottom: 0px;
    border: 1px solid black;
}
</style>
</head>
<body>
<p>Look, Ma, no JavaScript required.</p>
<div id='anchorRight'>Anchor right, 20% from top</div>
<div id='anchorBottom'>Anchor bottom, 20% from left</div>
<div id='anchorBoth'>Anchor bottom and right</div>
</body>
</html>

A pure CSS solution may not always be possible. When doing it with JavaScript, you'll have to watch not only for window resize events but also text resize, which is more of a pain (Google's Closure library includes utilities for doing that). Also be sure to build-in hysteresis to avoid repositioning your elements too frequently during the actual resize operation. (An easy way to do that is to respond to a resize by setting a function to be called by setTimeout a quarter second later and remembering the timer handle; if you get another resize event before the function is called, cancel the earlier timer and set a new one. You can set a max number of times you defer the resize before you go ahead [to show interim updates], but since moving these things with JavaScript may be a bit slow, you don't want to do it on every interim event you get during the operation.)

T.J. Crowder
+1: I'd only caution that the developer should check whether a percentage distance from the edges of the viewport is what he really wants.
Robusto
@Robusto: Oh, absolutely. I only used percentages in the example to demonstrate that one *can*. That may sully the point...
T.J. Crowder