Kyle Yeo
Kyle Yeo

Reputation: 2368

How do I center a dynamic div?

I'm not sure if this question has been answered (I think it probably has), but how do you center this dynamic div?

(I want #two to align itself to the middle position of #one.)

Right now my jsFiddle does this: http://jsfiddle.net/sE8Sc/4/

HTML :

<div id="one">
</div>
<div id="two">
        <a class="stuff">a</a>
        <a class="stuff">b</a>
        <a class="stuff">c</a>
</div>

CSS :

#one { width:100%; height:200px; background-color:#222; float:left; }
#two { text-align:center; float:left; }
.stuff { width:20px; height:20px; background-color:#444; margin:0 5px; float:left; }

I've tried margin:0 auto;, text-align:center; but still no dice. I'm not looking at declaring a defined margin like margin:0 41%; because if I wanted to add another <a class="stuff"> to the list it would get out of position...

Anyone? This is probably some simple positioning error that I can't figure out.

EDIT : I was looking around, and I saw this demo by Nivo Slider -- http://demo.dev7studios.com/nivo-slider/ -- how is it defining itself with a 960px width?

centered div

Upvotes: 0

Views: 81

Answers (2)

Kevin Lynch
Kevin Lynch

Reputation: 24703

You center a dynamic div by cimply giving it a display: table value

DEMO http://jsfiddle.net/kevinPHPkevin/sE8Sc/20/

#two {
    text-align:center;
    display: table;
    margin: 0 auto;
}

Upvotes: 0

Ian Clark
Ian Clark

Reputation: 9347

You'll need to wrap both #one and #two in a containing element. That should set the width. Then all you need to do is remove all the floats (on #one, #two and #two's children). JSFiddle

#wrapper { width:500px; }
#two { text-align:center;}
.stuff { width:20px; height:20px; background-color:#444; margin:0 5px; }

New markup.

<div id="wrapper">
    <div id="one"></div>
    <div id="two">
            <a class="stuff">a</a>
            <a class="stuff">b</a>
            <a class="stuff">c</a>
    </div>
</div>

Without the wrapper two would just be aligned to the center of your window (or a parent with a width).

Upvotes: 2

Related Questions