Expand container div with content width

2019-02-01 16:50发布

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.

6条回答
该账号已被封号
2楼-- · 2019-02-01 17:13

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

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-01 17:19

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.

查看更多
Anthone
4楼-- · 2019-02-01 17:21

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

查看更多
放我归山
5楼-- · 2019-02-01 17:27

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  
|                         |
+------------------------+
查看更多
Juvenile、少年°
6楼-- · 2019-02-01 17:34

Even easier:

<style>
    #container{ display: inline-block; }
</style>
查看更多
Deceive 欺骗
7楼-- · 2019-02-01 17:37

Something like this should work:

#container, #child_container, .child { 
    position: relative; 
    float: left;
}
查看更多
登录 后发表回答