2011-05-24 111 views
40

我在我的应用程序的结构如下:展开div容器与内容宽度

<div id="container"> 
    <div id="child_container"> 
    <div class="child"></div> 
    <div class="child"></div> 
    ... 
    <div class="child"></div> 
    </div> 
</div> 

每个孩子div有一个已知的固定宽度,但该应用程序允许更多的人在child_container div来插入。

我想要做的就是在需要的时候容器DIV水平扩展,考虑到子容器的总宽度。

这是目前发生的事情:

+------ container -------+ 
+--- child_container ----+ 
| child1 child2 child3 | 
| child4     | 
+------------------------+ 

如果我设置child_container DIV宽度为固定值,我可以得到它过去的div容器,尽管是一个有点难看,其工作水平扩展:

+------ container -------+ 
+------ child_container -+----+ 
| child1 child2 child3 child4 | 
+------------------------+----+ 

但是,这需要重新计算它,每当添加一个新的孩子。

有没有办法做到这一点,而无需使用固定宽度的子容器,在某种程度上使得最终的结果是

+--------- container ---------+ 
+------ child_container ------+ 
| child1 child2 child3 child4 | 
+-----------------------------+ 

感谢。

+0

请提供一些代码。在小提琴中更好。 – Andre 2011-05-24 18:55:43

+1

它是这样的:http://jsfiddle.net/8XGqs/ – Andre 2011-05-24 19:51:12

+0

http://jsfiddle.net/8XGqs/1/说明等效的ascii艺术以上更好,我认为。刚添加宽度:100%到#container。 – Andre 2011-05-24 19:59:51

回答

26

像这样的东西应该工作:

#container, #child_container, .child { 
    position: relative; 
    float: left; 
} 
+1

为什么'位置:相对'? – thirtydot 2011-05-24 19:10:52

+3

@thirtydot因为某些浏览器呈现html。不告诉它的位置有些浏览器将不使用“子”元素的大小,以增加集装箱 – wajiw 2011-05-24 19:13:38

+1

这是好事的大小...尽管你可能不需要'的位置是:相对;' – 2011-05-24 19:15:42

2

如果您将所有剩下的东西浮起来,包括包含div,它就会起作用。

28

即使简单:

<style> 
    #container{ display: inline-block; } 
</style> 
+0

我只是希望,IE7没有抛出一个合适的,每次使用该语句... – dkroy 2012-05-18 16:20:07

+3

易于处理这个[回答](http://stackoverflow.com/questions/ 6544852/ie7-problem-with-display-inline-block) – 2012-05-21 19:53:39

-7

刚刚设置的父的宽度到120%,做=)

+2

这将允许更多的元素,更多东西进来? – 2013-07-05 09:17:43

11

的父容器赢得”在增加子元素时增长。

+------ container -------+ 
+--- child_container ----+ 
| child1 child2 child3 | 
| child4     | 
+------------------------+ 

但我们可以通过使用css3弹性盒来避免在下一行上渲染新的。将样品置于下面提到的path

.products{ 
      display: -webkit-flex; 
      -webkit-flex-flow: row; 
      /*-webkit-justify-content: center;*/ 
     } 
     .products > div{ 
      padding: 0 4em; 
     } 

结果将是这样的:

+--- child_container ----+| 
| child1 child2 child3 ch|ild4 child5 
|       | 
+------------------------+