[英]Prevent elements from extending their parent DIV
我有两个div,包裹在一个容器div中。 底部的div包含一个动态填充的表格(宽度可变),该表格确定所有div的整体宽度。
在顶部div中,我要列出几个小的红色块(div或span或其他)。 这些红色块需要占用可用的水平空间,但是如果它们达到允许的最大宽度,则换行。
所以这就是我想要实现的:
不幸的是,我无法使其工作。 无论我如何对红色块(小的div浮动块或行内块)进行CSS编码,它们的宽度都超过了允许的范围。 结果,所有的div都变得比允许的宽得多,也比我的桌子宽了:
如何强制这些红色块仅使用allowed with,并在空间用尽时选择新行?
谢谢!
更新:这是一个工作示例,显示红色块(长度可变)彼此相邻,占用的宽度大于允许的宽度。 一旦达到表格的宽度,他们就需要从新的一行开始。 http://codepen.io/anon/pen/bqobGp?editors=1100#0
table td{
border:thin solid gray;
line-height:25px;
padding:0 5px;
}
.div1, .div2 {
margin-top:15px;
padding:20px;
background:white;
box-shadow:2px 0 3px rgba(0,0,0,.12)
}
.container {
display:inline-block;
background:#f1f1f1;
padding:30px;
}
.badge {
line-height:30px;
background:red;
min-width:150px;
color:white;
margin:5px 10px;
text-align:center;
font-family:sans-serif;
border-radius:5px;
display: inline-block;
}
根据我的历史经验,如果在父表元素上设置较小的宽度,则可以使用基本的HTML表实现这种行为。
因此:对于您的代码,我们可以使用display: table
和.container上的一小width
和white-space: nowrap;
对于.div2(以防止在表上换行),如下所示:
.container {
display: table;
width: 50px; /* use a small value */
...
}
.div2 {
white-space: nowrap;
}
这是更新的代码笔
/* shrink 2nd div to fit the table */
.div2 {width: fit-content;}
/* shrink first div to minimum size
* but constrain it to shrink no further than width established by its siblings
*/
.div1 {min-width: available; width: min-content;}
替代方法
.container {width: min-content;}
我不确定在CSS文件中您称其为“红色”块是什么,但是简短而又简单的方法是计算宽度。
例如:
.parent {
width: 100%;
padding: 0;
margin: 0;
background: green;
float: left;
}
.red_block {
width: calc(100% / 5 - 20px); /* Calculate width here - where it takes the full 100% of the parent and divides it by 5 "red blocks" and subtracts 20px for each */
height: 40px;
padding: 0;
margin: 10px;
background: red;
float: left;
}
<div class="parent">
<div class="red_block"></div>
<div class="red_block"></div>
<div class="red_block"></div>
<div class="red_block"></div>
<div class="red_block"></div>
<!-- Will wrap to second line -->
<div class="red_block"></div>
<div class="red_block"></div>
<div class="red_block"></div>
</div>
这回答了你的问题了吗?
更新:
通过宽度计算“红色块”,您甚至可以在某些媒体查询中指定该类,以根据您对移动设备的喜好更改宽度! 例:
@media screen and (max-width: 48em) {
.red_block {
width: calc(100% / 3); /* or to whatever you want...IE: width: 100%; */
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.