给定一个容器,里面有元素,如下所示:
<div id="container">
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
</div>
#container {
width: 600px;
border: 1px solid #CCC;
}
#container .item {
background: red;
display:inline-block;
width: 50px;
height: 50px;
}
有没有一种方法可以使用 CSS(无 JS)以等边距自动将元素居中。无需使用表格?
谢谢
最佳答案
将 text-align:center;
添加到容器中,使所有元素居中。
您不想使用表格,但您仍然可以告诉浏览器将其呈现为表格 :-) 那么这个 CSS 怎么样:
#container {
width: 600px;
border: 1px solid #CCC;
display: table;
border-spacing:20px 0; /* this is the value that controls the margin */
}
#container .item {
background: red;
display: table-cell;
width: 50px;
height: 50px;
}
关于html - 如何在div中动态居中元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6447937/