views:

958

answers:

3

Hi,

I have some divs that are set with position absolute (CSS) when the page is ready, and are positioned relative to another fixed div, wich works fine. However, before the page is loaded and everything is set, if the page is resized, those absolute divs don't follow the changes, moving to other places, wich I think they are given values relative to top and left of the screen.

The position of the relative div I use as starting point to position the absolute ones may change position as well, relative to the ones above it.

Is there any way to listen the changes in the browser's width / height in order to make those divs stay placed in the right position.

Thanks in advance!

A: 

There are ways to listen to changes using JavaScript, buit doesn't "position: fixed" already solve your problem?

Pekka
No, it doesn't, because "position: fixed" follows the scroll of the browser, loosing the position relative to another div that I need.
yoda
A: 

It may not be necessary to use JavaScript if you only need to position your element(s) relative to another element instead of the overall document. You can use "position:relative":

<div id="myContainer" style="position:relative">

    <div id="myElement" style="position:absolute;left:100px;"></div>

</div>

Because myContainer has position:relative, myElement will be positioned absolutely but relative to myContainer instead of relative to the overall document. Armed with this, you can construct quite elaborate, but robust positions that will be browser-size-agnostic.

Rex M
thanks for pointing it, I forgot to say that the position of the element wich i use as "anchor" to the absolute has his position changed when the divs above change their height, after the page is loaded. Also, the page itself is centered in the screen.
yoda
+3  A: 

First you want to start with binding the window resize event to a function of your choosing.

$(window).bind("resize", methodToFixLayout);

Now you can determine the new heights and widths and make adjustments to the page from there.

function methodToFixLayout( e ) {
    var winHeight = $(window).height();
    var winWidth = $(window).width();
    //adjust elements css etc.....
    //$("#someDiv").css('someProperty',someValue based on winHeight and winWidth);
}

Without more specifics on your layout it's hard to tell what changes you'll need exactly but this should get you going in the right direction.

r-dub
Thanks! I managed to do the calculations with the resize event, in some very small lines of code, much less than I expected!
yoda
Nice, i'm glad it worked for you.
r-dub