Search code examples
javascripthtmlcsscss-floatcenter

How to center a div with dynamic & static content?


Ok, I have the following HTML:

<div id="header">
    <div id="header_inner">
        <div id="header_image">
            <a href=""><img src="..."/></a>
        </div>
        <div id="header_content">
            <h1 id="header_content_h1">Dynamic Content</h1>
        </div>
    </div>
</div>

And I want to center the div with id header_inner.

But my issue is that the div with id header_content contains dynamic content, so it can be any width.

Currently I solve this by setting the width of header_inner using Javascript at window.onload and the normal css for centering div's (margin:auto;), but this causes the content to load initially on the left of the page and then jump to the center after a few milliseconds. The jump is very noticeable on the live website.

JSFiddle: http://jsfiddle.net/wprggrm2/4/

*The jump doesn't show up in the JSFiddle, but it does on the live site; this is just to show you how I'm doing it in action!

So any ideas for alternative solutions that would avoid this jump? I mean I'm guessing this is a common situation.


Solution

  • You can use display:inline-block on header-inner and text-align:center on header.

    #header {
        width: 100%;
        display: inline-block;
        text-align: center;
    }
    #header_inner {
        display:inline-block;
    }
    

    Updated fiddle: http://jsfiddle.net/wprggrm2/5/