这里有问题的代码和演示版本。 如果你看到最后两个黑盒子在中央有没有办法让它们显示在左侧?
mainparent
{
width:500px;
height:200px;
text-align:center;
background:#ccc;
}
.boxes
{
width:50px;
height:50px;
display:inline-block;
margin-left:5px;
background:#000;
}
答案 0 :(得分:1)
将您的CSS #mainparent
text-align
更改为left
。
答案 1 :(得分:1)
由于您已经有了答案,另一种方法是使用CSS选择器
#mainparent
{
width:500px;
height:200px;
text-align:center;
background:#ccc;
}
.boxes
{
width:50px;
height:50px;
display:inline-block;
margin-left:5px;
background:#000;
}
.boxes:nth-child(17)
{float:left; margin-left:21px;}
.boxes:nth-child(18)
{float:left; margin-left:9px;}
你仍然需要做的工作才能使布局正确,它只有在你有固定数量的盒子等时才有效,但是你可能会发现这种方法很有用(或者知道不再使用它会很糟糕!)
答案 2 :(得分:1)
为什么不把它们漂浮下去? (并调整容器大小以适应它们。)
这样您就可以更好地控制边距,因为font-size
不影响它们(也不是空白)
#mainparent
{
width:480px;
height:200px;
background:#ccc;
}
.boxes
{
width:50px;
height:50px;
float:left;
margin:5px;
background:#000;
}
演示
更新
如果你想让元素在它们之间保持对齐但在它们的容器中居中对齐,你将需要中间的另一个元素和一些javascript ..
这是一个jquery实现
<强> HTML 强>
<div id="mainparent">
<div class="centerized">
<div class="boxes"></div>
<div class="boxes"></div>
<div class="boxes"></div>
..
..
<div class="boxes"></div>
<div class="boxes"></div>
<div class="boxes"></div>
</div>
</div>
<强> CSS 强>
#mainparent
{
background:#ccc;
}
.centerized{
overflow:hidden; // to grow according to the boxes
margin:0 auto; // to be centered in container
}
<强> jquery的强>
$(function(){
// cache the repeatedly used elements
// and fixed values
var main = $('#mainparent'),
centerized = main.find('.centerized'),
itemWidth = main.find('.boxes').outerWidth(true);
$(window).resize(function(){
var fitItems = (main.width() / itemWidth) | 0;
centerized.width(fitItems * itemWidth);
}).trigger('resize');
});