繁体   English   中英

css内联块元素,当使用text-align:center在父div上时,最后一个子项向左浮动

[英]css inline-block elements, last child to float left when using text-align:center on parent div

在这里,您有问题的代码和演示版本。 如果你看到最后两个黑盒子在中央有没有办法让它们显示在左侧?

mainparent
{
  width:500px;
  height:200px;
  text-align:center;
  background:#ccc;
}
.boxes
{
  width:50px;
  height:50px;
  display:inline-block;
  margin-left:5px;
  background:#000;
}

DEMO

将CSS #mainparent text-align更改为left

由于您已经有了答案,另一种方法是使用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;}

的jsfiddle

你仍然有工作要做,以使布局正确,它只有当你有固定数量的盒子等时才有效,但你可能会发现这种方法很有用(或者知道不再使用它会很糟糕!)

为什么不把它们漂浮? 并调整容器大小以适应它们..

这样你可以更好地控制边距,因为font-size不会影响它们( 不会影响空白

#mainparent
{
    width:480px;
    height:200px;
    background:#ccc;
}
.boxes
{
    width:50px;
    height:50px;
    float:left;
    margin:5px;
    background:#000;
}

演示http://jsfiddle.net/JxhP8/32/


更新

如果你想让元素在它们之间保持对齐但在它们的容器中居中对齐,你将需要中间的另一个元素和一些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');
});

演示 http://jsfiddle.net/JxhP8/34/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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