防止元素扩展其父DIV

时间:2017-03-14 15:04:41

标签: html css css3

我有两个div,包裹在一个容器div中。底部div包含一个动态填充的表(具有可变宽度),它决定了所有div的总宽度。

在顶部div中,我想列出几个小红色块(div或span或其他)。这些红色块需要占用可用的水平空间,但如果它们达到最大允许宽度,则换行到新行。

所以这就是我想要实现的目标:

enter image description here

不幸的是,我无法让它发挥作用。无论我如何CSS红色块(小浮动div或内联块),他们继续采取比允许更多的宽度。结果,所有div都变得比允许的宽得多,比我的桌子宽:

enter image description here

如何强制这些红色块仅使用允许的,如果空间不足则选择一个新行?

谢谢!

更新 这是一个工作示例,显示彼此相邻的红色块(具有可变长度),占用的宽度超过允许的宽度。一旦达到表格宽度,他​​们就需要在新行上开始。 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;
}

3 个答案:

答案 0 :(得分:2)

根据我的历史经验,如果在父表元素上设置小宽度,则可以使用基本HTML表实现此类行为...

因此:对于您的代码,我们可以在.container上使用display: table和小width,在.div2上使用white-space: nowrap;(以防止表格上的换行符),如下所示:

.container {
  display: table; 
  width: 50px; /* use a small value */
  ...
}

.div2 {
  white-space: nowrap; 
}

这是updated code pen

答案 1 :(得分:1)

/* 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;}

这些width values相当新,the spec仍在不断变化,因此不同的浏览器可能会以不同的名称或前缀支持它们。

答案 2 :(得分:-1)

我不确定你称之为" red"你的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>

<强> DEMO

这会回答你的问题吗?

<强>更新

使用&#34;红色块&#34;通过宽度计算,您甚至可以在某些媒体查询中指定该类,以根据您的喜好更改移动设备的宽度!例如:

@media screen and (max-width: 48em) {
    .red_block {
      width: calc(100% / 3); /* or to whatever you want...IE: width: 100%; */
    }
}
相关问题