Click to See Complete Forum and Search --> : [RESOLVED] Centering Divs with position:absolute


shane.carr
11-18-2006, 12:49 PM
Hi! How do you center absolutely positioned divs? I have found two possible ways, but neither of which work as desired:

There's a way on this ancient thread (#334!) but you must know the width of the div to make it work (http://www.webdeveloper.com/forum/showthread.php?t=334)

I also discovered this way myself:

<div style="position:absolute; top:650px; width:100%;">
<div style="position:relative; margin:0 auto; text-align:center;">

this text is centered<br />
<img style="margin:0 auto;" />and so is this picture

</div>
</div>

But the horizontal scroll-bar is active, when the window's 750px wide and 2000px wide. And it stays at the same width (see attached images).



So, what's the best way to center absolutely positioned objects?

holyhttp
11-18-2006, 05:18 PM
Hi Shane,

The whole point behind the absolute positioning is to lock a given layer in certain coordinates within a container (screen or another layer with relative positioning).
Once you choose absolute postioning, then your web browser has no longer the latitude to center that specific layer.
To avoid the scrollbar make sure the container layer is set to "overflow:hidden/visible".
In your case I suspect the "margin: 0 auto" in the img tag.

shane.carr
11-19-2006, 12:16 PM
The only reason that I needed to use absolute positioning was because the divs above it were to move by javascript, and I didn't want these things to move.

I found my problem though - If I add "margin-left:0px;left:0px;" to the top div, then it works fine.


So, for future reference:

How to center the contents of an absolutelly positioned div:


<div style="position:absolute; top:#px; width:100%; margin-left:0px; left:0px; text-align:center;">

This text is centered.<br />
<img style="margin:0 auto;" /><br />this picture is too.

<!-- note that to center block objects, "margin:0 auto;" must be executed in the style -->

</div>