2

我需要将蓝色容器内的黄色框(无论有多少)居中对齐。如果黄色框很多,它们可以放在第 2 行(或第 3 行等),但它们应该在蓝色容器内保持居中对齐。任何想法如何做到这一点?

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/

4

4 回答 4

3

移除 div 上的浮点数并将其替换为 display:inline-block。在容器 div 中添加 text-align:center 规则:

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

jsFiddle 示例

于 2013-09-16T20:07:36.237 回答
1

你可以试试display:inline-block;

更改您的 CSS,例如:-

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

演示 JSFIDDLE

于 2013-09-16T20:04:40.187 回答
1

将您的CSS更改为以下内容:

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

.box { width:10em; display:inline-block; background:yellow; }
于 2013-09-16T20:09:27.440 回答
1

我不知道您是否使用自动边距会起作用.. 但我建议您将其作为菜单处理。它将像 div 一样工作。我以这种方式向您展示,因为这就是我确定它有效的方式。

<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>

的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;
}

那就是你想要的?或者您希望在蓝色 div 内自动调整所有黄色框?

于 2013-09-16T20:09:38.130 回答