Expand container div with content width

和自甴很熟 提交于 2019-11-28 22:01:06

问题


I have the following structure in my application:

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

Each child div has a known fixed width, but the application allows more of them to be inserted in the child_container div.

What I'm trying to do is to have the container div expand horizontally when needed, given the total width of the child container.

This is what happens currently:

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

If I set the child_container div width to a fixed value, I can get it to expand horizontally past the container div, which works despite being a bit ugly:

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

However, that requires recalculating it whenever a new child is added.

Is there a way to do this without using fixed widths for child container, in a way such that the end result is

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

Thanks.


回答1:


Something like this should work:

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



回答2:


Even easier:

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



回答3:


The parent container won't grow when a child element is added.

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

but we can avoid the rendering of new one on the next line by using css3 flex box. The sample is placed the below mentioned path

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

The result will look like this:

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



回答4:


If you float everything left including the containing divs, it will work.




回答5:


The modern solution today would be

#child_container {
    display: flex;
}

Because flex-wrap is by default set to

flex-wrap: nowrap;

This simple solution works like a charm. And by now also in all relevant browsers.




回答6:


just set the width of the parent to 120% and done =)



来源:https://stackoverflow.com/questions/6115353/expand-container-div-with-content-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!