blog icon indicating copy to clipboard operation
blog copied to clipboard

flex 项中子元素文本溢出截断 text-overflow:ellipsis 失效问题 – flexbox 布局中 flex 项的宽度计算原理

Open ly2011 opened this issue 7 years ago • 0 comments

问题

flexbox 布局时 flex 项子元素中的文本溢出后想显示省略号(…),结果设置 text-overflow:ellipsis 后没效果:

HTML代码:

  <div class="flex">
    <div class="col1">图标</div>
    <div class="col2">
      <div class="item-con">
        flexbox 布局旨在提供一个更有效地布局、对齐方式,并且能够使容器中的子元素大小未知或动态变化情况下仍然能够分配好子元素之间的空间。
      </div>
    </div>
  </div>

CSS 代码:

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.flex {
  width: 320px;
  padding: 5px 10px;
  display: flex;
  border-bottom: 1px solid #eee;
  font-size: 32px;
}

.flex .col1 {
  margin-right: 6px;
  color: #999;
}

.flex .col2 {
  flex: 1;
  min-width: 0; /* 解决方案 */
}

.flex .col2 .item-con {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

我们看到 .col2 设置 flex: 1; , .item-con 设置了 text-overflow:ellipsis ,但是文本还是溢出了。

这种布局在移动端页面开发时候经常遇到,我们不能为 .item-con 元素设置个宽度,这样就无法适应不同屏幕尺寸的终端设备。

解决方案: 在flex项中设置 min-width: 0;

解决方案是在 flex 项(上例子中 .col2元素)中设置 min-width:0;, 当然也可以设置其他合适的 min-width 值。

ly2011 avatar Dec 09 '18 02:12 ly2011