【问题标题】:css inline-block elements, last child to float left when using text-align:center on parent divcss inline-block 元素,在父 div 上使用 text-align:center 时最后一个子元素向左浮动
【发布时间】:2013-12-04 01:33:57
【问题描述】:

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

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

DEMO

【问题讨论】:

  • 添加这个:#mainparent {text-align:left;}
  • 我认为 OP 不想破坏他对所有框的原始对齐

标签: css text-align


【解决方案1】:

为什么不让它们向左浮动呢? (并调整你的容器大小以适应它们..

这样您可以更好地控制边距,因为 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/

【讨论】:

  • 当屏幕变大或变小时会发生什么:)
  • 因为我希望它具有响应性,并且在真实网站中,父 div 的宽度为 100%。
  • 但是 li 元素现在没有居中 hmm
  • 你不能同时拥有这两个条件(居中对齐和左对齐..)。您将不得不使用 js 来调整容器的大小以完全适合内容并将容器居中..
  • @AXheladini,您需要包含 jquery(如果您仍有问题,请将链接发布到您的实时站点,以便我查看
【解决方案2】:

将您的 CSS #mainparent text-align 更改为 left

【讨论】:

  • 子元素不会在父 div 中居中!
  • 我猜你将不得不接受@DaveRook 的回答。
【解决方案3】:

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

您仍然需要做一些工作才能使布局正确,它仅在您有固定数量的盒子等时才有效,但您可能会发现这种方法很有用(或者知道不再使用它太可怕了!)

【讨论】:

  • 这样最后两个元素到最左边,这不是我想要的!
  • 我需要它来响应。这样它在不同的屏幕上看起来不会很好。可能有一些 javascript 解决方案!
猜你喜欢
  • 1970-01-01
  • 2014-08-03
  • 2013-05-20
  • 2011-11-06
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多