Horizontally Center a Div (regardless of parentage)

Hi Folks,

I have a need to horizontally center a div on a page regardless of parentage. That is, wherever this bit of markup gets generated, inside another div, an ol, whatever, to the absolute center of the page it must go. I’m halfway there; as long as the markup is directly inside the body of my page, all is well. Inside other containers however, I just can’t seem to make it work. Here is the work in progress:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/transitional.dtd">
<html>
    <head>
            <style type="text/css">
            h1.Warning         {    color: red;   padding-bottom: 0px; margin-bottom: 0px; padding-top: 0px; margin-top: 0px;}
            h1.Caution         {    color: black; padding-bottom: 0px; margin-bottom: 0px; padding-top: 0px; margin-top: 0px;}
            h1.Note            {    color: blue;  padding-bottom: 0px; margin-bottom: 0px; padding-top: 0px; margin-top: 0px;}

            table.Warning      {    border: dashed red 4px; padding-right: 2px; padding-left: 2px;}
            table.Caution      {    background: yellow; border: dashed black 4px; padding-right: 2px; padding-left: 2px;}
            table.Note         {    border: solid black 4px; padding-right: 2px padding-left: 2px;}

            .ncw-container {    position: relative;
                                    width: 100%;
                                    min-width: 100px;
                               }

            .ncw-center    {    position: absolute;
                                    width: 50%;
                                    top: 0px;
                                    left: 50%;
                                    height: 0px;
                               }

            .ncw-table         {    position: relative;
                                    display: inline-block;
                                    left: -50%;
                               }
</style>
        <script language="javascript">
            function centerWCN()
            {
                var containerDivs = document.getElementsByTagName("div");
                for (var i = 0; i < containerDivs.length; i++)
                {
                    var containerDiv = containerDivs[i];
                    if (containerDiv.className == "ncw-container")
                    {
                        var tables = containerDiv.getElementsByTagName("table");
                        var tableHeight = 0;
                        for (var j = 0; j < tables.length; j++)
                        {
                           var table = tables[j];
                           if (table.className == "ncw-table")
                           {
                               tableHeight = tableHeight + table.clientHeight;
                           }
                        }

                        containerDiv.style.height = tableHeight + 'px';
                    }
                }
            }

            function OnResize()
            {
                centerWCN();
            }
        </script>
    </head>

    <body OnResize="OnResize()">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ultrices felis et neque egestas suscipit. Donec tortor odio, pulvinar non tristique ac, imperdiet sed libero. Nulla facilisi. Integer nisi nulla, consectetur auctor laoreet sed, gravida non nulla. Cras volutpat aliquet volutpat. Sed ligula nibh, feugiat at sollicitudin sit amet, dignissim eget velit. Aenean consectetur aliquam urna, non mattis risus dictum ac. In hac habitasse platea dictumst. Sed ac magna metus.  Nulla facilisi. Integer nisi nulla, consectetur auctor laoreet sed, gravida non nulla. Cras volutpat aliquet volutpat. Sed ligula nibh, feugiat at sollicitudin sit amet, dignissim eget velit. Aenean consectetur aliquam urna, non mattis risus dictum ac. In hac habitasse platea dictumst. Sed ac magna metus</p>
            <div class="ncw-container">
                <div class="ncw-center">
                    <table class="ncw-table">
                        <tr>
                            <td align="center" valign="top">
                                <table width="10*%" class="Warning">
                                    <tr>
                                        <td align="center" valign="top">
                                            <h1 class="Warning">WARNING</h1>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td class="ncw">
                                <p class="ncw" id="">Lorem ipsum dolor sit amet</p>
                            </td>
                        </tr>
                        <tr>
                            <td class="ncw">
                                <p class="ncw" id="">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ultrices felis et neque egestas suscipit.</p>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ultrices felis et neque egestas suscipit. Donec tortor odio, pulvinar non tristique ac, imperdiet sed libero. Nulla facilisi. Integer nisi nulla, consectetur auctor laoreet sed, gravida non nulla. Cras volutpat aliquet volutpat. Sed ligula nibh, feugiat at sollicitudin sit amet, dignissim eget velit. Aenean consectetur aliquam urna, non mattis risus dictum ac. In hac habitasse platea dictumst. Sed ac magna metus.  Nulla facilisi. Integer nisi nulla, consectetur auctor laoreet sed, gravida non nulla. Cras volutpat aliquet volutpat. Sed ligula nibh, feugiat at sollicitudin sit amet, dignissim eget velit. Aenean consectetur aliquam urna, non mattis risus dictum ac. In hac habitasse platea dictumst. Sed ac magna metus</p>
    </body>
</html>

A few requirements:

  1. Individual lines must not be centered, thus the centering of a table, rather than just using naked p elements or somesuch.
  2. The Warning, Caution, Note banners should not get stretched, so they have their own container.
  3. Production environment is IE7 / CSS2.

I saw a few solutions on various forums where folks proposed inverting the absolute div to the outside or used two absolute divs, however, this only seems to work in cases where you are willing to set fixed dimensions on the divs. I can’t do that. The Warning, Caution and Note text must flow up to the width of the page. I’ve also tried dynamically setting the height of one or both absolute divs in the javascript, but this seems to get ignored and the text just bleeds onto the next paragraph.

I’d love to ditch the javascript, but once in the realm of absolute-ism, I couldn’t see a way around it.

Thanks,

Eric

Hello Eric,

not wanting to be negative, but.
DO NOT USE TABLES UNLESS FOR TABULAR DATA.
There is NO reason in this world to be using tables for anything else!

That said, what exactly are you trying to achieve here?
The way I’ve understood it, you are trying to overlay the contents of a page with a static box, thus making them inaccessible?
Or is this supposed to be a dialog box that one can click away?

In my dynamically generated pages, I need warnings, cautions and notes to always align to the center of the page, regardless of the current level of indentation, without treading on or interrupting the layout of elements that occur before and after said warnings, cautions and notes.

Here is one way to do as you asked. If you don’t know how much will be inserted into the div then you could make a scrollbar to handle overflow. http://www.websitecodetutorials.com/code/css/css-vertical-&-horizontal-centered-div.php

Thank you very much, I was able to use this approach as a basis for a solution.

I would use position:fixed; that way the centering occurs relative to the viewport and NOT the parent element. There is a drawback, that the element must have fixed dimensions, and must not exceed the view port dimensions or content will be inaccessible ( this is just logic) , so to be safe I would ad overflow:auto;


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style type="text/css">
body {
height:100%; 
margin:0; 
padding:0;
}
h1 {
font-size:1.2em;
margin:20px 0 0;
font-family:Arial;
text-align:center;
}
.mid {
position:fixed; 
width: 70%;
height:70%;
top:15%;  /* 1/2 * (100%-height) */
left:15%; /* 1/2 * (100%-width) */
margin: -2px 0 0 -2px; /* to compensate for border; BUT ALSO to  show how to mix PX uints and % units when centering*/
overflow:auto;
border:2px solid #000;
background:#CCC;
}
ul {margin:0; padding:0;}
li {list-style:none; 
	position: relative;/*just to to prove it works in   tricky situations*/}
</style> 
</head>
<body>
<ul>
 <li>list item</li>
 <li><div class="mid">
<h1>Dead center an element </h1>  
</div></li>
 <li>list item</li>
 <li>list item</li>
</ul>
</body>
</html>