中心浮动子DIV在具有流体宽度的父DIV [英] Center floated child DIVs in a parent DIV that has fluid width

查看:117
本文介绍了中心浮动子DIV在具有流体宽度的父DIV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML:

<div id="parent">
     <div class="child">Box1</div>
     <div class="child">Box2</div>
     <div class="child">Box3</div>
     <div class="child">Box4</div>
     <div class="child">Box5</div>
     <div class="child">Box6</div>
     <div class="child">Box7</div>
     <div class="child">Box8</div>
     <div class="child">Box9</div>
     <div class="child">Box10</div>
</div>

和以下CSS:

#parent {
   display: inline-block;
   max-width: 1000px;
   height: 500px;
   border: 1px solid #000000;
   text-align: center;
}
.child {
   width: 100px;
   height: 100px;
   border: 1px solid #000000;
   margin: 10px;
   float: left;
}

我想向左浮动子DIV,父DIV不具有固定宽度。

I want to float left the child DIVs and at the same time center them in the parent DIV that does't have a fixed width.

我不想对子DIV使用display:inline-block的原因是,如果一行只有1或2个框,它们将居中,我希望他们在左边与上一行的框对齐。

The reason I don't want to use display: inline-block for the child DIVs is that if a row has only 1 or 2 boxes , they will be centred and i want them to be aligned to the left with the boxes on the previous rows.

第二个原因是更多的数据将使用ajax加载。因此,如果最后一行只有1或2个框,并且仍然可以容纳更多的框,它们将被插入一个新行,而不是附加到最后一行。我不知道这一点,但我认为,当使用显示内联块时会发生什么。 Float没有这种行为。

The second reason is that more data will be loaded using ajax. So, if the last row has only 1 or 2 boxes and still can accommodate more boxes, they will be inserted into a new line instead of being appended to the last row. I'm not sure of this point but I think that what would happen when using display inline-block. Float instead doesn't have this behaviour.

忘了提到父类应该显示:inline-block,因为另一个框会在它旁边对齐。

Forgot to mention that the parent should be display: inline-block because another box will be aligned next to it.

我为你演奏了一个小提琴:
http: //jsfiddle.net/6a2eqpmu/

I created a fiddle for you to play with: http://jsfiddle.net/6a2eqpmu/

推荐答案

很遗憾,您无法使用纯CSS执行此操作。如果你愿意使用一点javascript和jQuery,你可以轻松实现你想要的:

Unfortunately you are unable to do this using pure css. If you are willing to use a bit of javascript and jQuery you can easily achieve what you want:

var parent = $('#parent'),
    container = $('#container'),
    children = container.children('.child'),
    width = children.eq(0).outerWidth() + parseInt(children.eq(0).css('margin-left')) + parseInt(children.eq(0).css('margin-right')),
    maxWidth = children.length * width;

function resizeContainer() {
    var newWidth = Math.floor(parent.width() / width) * width;
    if (newWidth <= maxWidth && newWidth > 0) {
        container.width(newWidth);
    }
}

$(window).resize(resizeContainer);

resizeContainer();

示例

这篇关于中心浮动子DIV在具有流体宽度的父DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆