Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need help CSS centering with absolute positioning

I've never been totally satisfied with my various solutions to centering content in a web page. the <center> tag has been deprecated back in the middle of the 18th century, but I fail to see a reasonable alternative. Specifically what I want is to have a parent DIV that is centered, but against whose upper left hand corner I can set things "absolutely".

Is there a way to accomplish this without using window.onresize javascript that remeasures everything? It seems like a fairly straight forward idea... I want things absolutely positioned, I just want the 0,0 coordinate to be relative to something other than the top left corner of the browser window.

Right now, what I do is set a div to center its content and then noodle around with relative positioning, but that's very tiresome because relative objects keep pushing each other around in ways that I totally don't want.

Any and all thoughts on this greatly appreciated.

like image 695
Yevgeny Simkin Avatar asked Jun 23 '09 18:06

Yevgeny Simkin


People also ask

How do I center align an absolute div?

using a "text-align: center;" and a "left: 0; right: 0;" will allow you to absolute position a div while keeping it horizontally centered.

How do you center vertically using absolute position?

A common technique for both horizontal and vertical centering is using an absolute positioned element as child of a relative parent. What we do is basically position our child element left by 50% and we shift it back by half of its size using a negative 50% translateX in order to get it centered.


1 Answers

body { text-align: center; }
#wrapper { width: 960px; margin: 0 auto; text-align: left; position: relative; }
#wrapper .child { position: absolute; left: 0; top: 0; }

Just example code, but any .child element would be at 0,0 of the wrapper

Any absolutely positioned element will absolutely position to it's nearest position-relative parent. If an element doesn't have a parent with position relative, it just uses the document. Below is an example without classes (some color and width styles added for clarity).

<html>
    <body style="text-align: center;">
        <div style="position: relative; width: 100px; height: 100px; margin: 0 auto; background: red;">
            <div style="position: absolute; left: 0; top: 0;">
                This will absolutely position relative to the container div.
            </div>
        </div>
        <div style="position: absolute; left: 0; top: 0; width: 100px; height: 100px; background: blue;">
            This will absolutely position relative to the document
        </div>
    </body>
</html>
like image 94
Mike Robinson Avatar answered Oct 20 '22 04:10

Mike Robinson