首页 > 解决方案 > 动态宽度溢出flex容器的flex项

问题描述

请参阅此代码示例 [ 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中是否对此有任何修复

标签: htmlcssflexbox

解决方案


您只需要允许第二个 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>


推荐阅读