html - 如何对齐到中心 float 的 div?

标签 html css

我需要将蓝色容器内的黄色框(无论它们有多少)居中对齐。如果黄色框很多,它们可以在第二行(或第三行等)下降,但它们应在蓝色容器内保持居中对齐。有什么想法吗?

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/

最佳答案

移除 div 上的 float 并将其替换为 display:inline-block。将 text-align:center 规则添加到容器 div:

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

jsFiddle example

关于html - 如何对齐到中心 float 的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18836308/

相关文章:

jquery - HTML 切换开关状态

javascript - 使用 setInterval() 刷新图像

javascript - 是否有原因导致括号运算符 [] 可能无法在 React 组件中与 getElementsByClassName() 一起使用?

html - 如何在单击单选按钮时显示 CSS 边框

javascript - 将滚动条添加到附加框

html - 如何正确转义 HTML 属性中的引号?

mysql - 如何从第一张表的customer_id获取第二张表的customer_id?

html - CSS 属性指定字符串可以在哪些字符上断开

javascript - 奇怪的 Bootstrap 输入组行为

html - 一个输入有几个不同的类?,怎么回事?