Horizontally-centering an absolute position to match a relative position

Posted by Chris Vandevelde on Stack Overflow See other posts from Stack Overflow or by Chris Vandevelde
Published on 2010-05-25T15:07:52Z Indexed on 2010/05/25 15:11 UTC
Read the original article Hit count: 232

Filed under:
|
|
|

I'm trying to make a div box, containing various elements, fixed at the top of the page once the page has been scrolled so that the box would normally be out of view, but scroll normally until that point (like the behaviour at http://perldoc.perl.org/perl.html).

The conditionally-fixed part is pretty simple to implement (set the position to "fixed" once the user has scrolled past a certain point, and "static" once it's scrolled back up), but I'm having trouble with the positioning and dimensions; it screws up if I'm not specifying an absolute position (if I'm using % or "auto", rather than px, em, cm, etc.) or it, confusingly, left-aligns if the box is less than the width of the page. I can understand why, more or less, I'm just trying to fix it.

My strategy right now is to have an invisible DIV hold the place of the box and use Prototype's clonePosition() function to hold its position, but it doesn't seem to work for some reason. Neither does copying the margin from one element to the other. Any ideas?

Bonus points and eternal gratitude if you can come up with an idea that will adjust itself with the browser window (like auto margins) without setting an onresize event.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about prototype