动态宽度溢出flex容器的flex项目

时间:2020-05-06 14:34:53

标签: html css flexbox

请参阅此代码示例 [https://codepen.io/him10meena/pen/xxwYRxo][1]

//html
    <div class="row">
      <div class="div1">fixLengthText</div>
      <div class="div2">this text is dynamic and can be very very very very very very very long</div>
      <div class="div3">fixLengthText</div>
    </div>

     <p>
      i want the middle div to be contained inside the parent div with overflow ...
    </p>


//css
/* important stuff for this example */


.row {
  width: 500px;
  display:flex;
  flex-direction: row;
  flex-wrap: nowrap;
}
.div1,.div2,.div3 {
  flex: 0 0 auto;

}


/* other stuff */
div {
  padding:1em;
  margin:0.2em;
  background-color: rgba(0,0,0,0.125)
}


我的第一列和最后一列具有固定长度的字符串,该字符串是静态的,但是我的中层div可以具有任何长度的字符串,并且它溢出示例链接中所示的父flex容器

所以我想让它的宽度等于它的内容,并且一旦内容开始增长超过其容量,它就应该显示为省略号。 ...

我只希望一行中所有3个div的内容没有任何换行。我更喜欢在div2上不设置最大宽度或显式宽度的解决方案(因为我的整个div宽度是基于设备分辨率的,因此我在链接中给出了固定值,仅供参考)。只是好奇flex是否有解决办法

1 个答案:

答案 0 :(得分:1)

您只需要允许第二个div缩小,然后为省略号溢出添加通用属性:

.row {
  width: 500px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}

.div1,
.div2,
.div3 {
  flex: 0 0 auto;
}


/* other stuff */
div {
  padding: 1em;
  margin: 0.2em;
  background-color: rgba(0, 0, 0, 0.125)
}

.div2 {
  flex-shrink:1;
  text-overflow:ellipsis;
  white-space:nowrap;
  overflow:hidden;
}
<div class="row">
  <div class="div1">fixLengthText</div>
  <div class="div2">this text is dynamic and can be very very very very very very very long</div>
  <div class="div3">fixLengthText</div>
</div>

<p>
  i want the middle div to be contained inside the parent div with overflow ...
</p>