使用内容宽度扩展容器 div
我的应用程序具有以下结构:
<div id="container">
<div id="child_container">
<div class="child"></div>
<div class="child"></div>
...
<div class="child"></div>
</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 |
+-----------------------------+
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
更简单:
Even easier:
像这样的东西应该有效:
Something like this should work:
添加子元素时,父容器不会增长。
但我们可以通过使用 css3 flex box 避免在下一行渲染新的。该示例放置在下面提到的 路径
结果将如下所示:
The parent container won't grow when a child element is added.
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
The result will look like this:
如果你浮动剩下的所有内容,包括包含的 div,它就会起作用。
If you float everything left including the containing divs, it will work.
今天的现代解决方案是
因为
flex-wrap
默认设置为这个简单的解决方案就像一个魅力。现在也在所有相关浏览器中。
The modern solution today would be
Because
flex-wrap
is by default set toThis simple solution works like a charm. And by now also in all relevant browsers.
只需将父级的宽度设置为 120% 即可完成 =)
just set the width of the parent to 120% and done =)