简体   繁体   中英

How can I align to center floated divs?

I need to center align the yellow boxes (no matter how many are they) inside the blue container. The yellow boxes can go down on the 2nd (or 3rd row, etc) if they are many but they should remain center aligned inside the blue container. Any ideas how to do it?

HTML

<div id="container">test
    <br />
    <div class="box">foo bar</div>
    <div class="box">foo bar</div>
    <div class="box">foo bar</div>
    <div class="box">foo bar</div>
</div>

CSS

#container {
    background:lightblue;
    width:100%;
}
.box {
    width:10em;
    float:left;
    background:yellow;
    margin:1em;
}

http://jsfiddle.net/585Eq/

Remove the float on the divs and replace it with display:inline-block. Add a text-align:center rule to the container div:

#container {
    background:lightblue;
    width:100%;
    text-align:center;
}
.box {
    width:10em;
    display:inline-block;
    background:yellow;
    margin:1em;
}

jsFiddle example

You may try with display:inline-block;

Change your CSS like:-

#container {background:lightblue;width:100%; text-align:center;}
.box {width:10em; display:inline-block; background:yellow; margin:1em;
}

DEMO JSFIDDLE

Change your css to following:

#container { background:lightblue; width:100%;text-align:center }

.box { width:10em; display:inline-block; background:yellow; }

I dont know if you use auto margin will work.. but i recommend you to deal with it as a menu. It will work just like a div. Im showing you this way because thats the way im sure it works.

<ul id="container">test
    <br />
    <li class="box">foo bar</li>
    <li class="box">foo bar</li>
    <li class="box">foo bar</li>
    <li class="box">foo bar</li>
</ul>

the CSS:

#container {
    text-align: center;
    height: <-- Specify a fixed height.
}
#container li {
    display: inline-block;
    margin-right: 30px; <-- This will the the margin between the items
    list-style-type: none;
}

Thats what you want? Or you want that all the yellow boxes be automatically adjusted inside the blue div?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM