需求:需要在flex子元素中通过overflow:hidden设置文字超出隐藏。

问题描述:在对子元素设置具体的宽度后,overflow属性可以正常生效。但是如果需要子元素自适应宽度(设为width:100%,calc(100% -100px),flex:1)等等,子元素中的overflow均不能正常生效。

参考如下:

HTML部分:
<div class="father">
    <div class="son">
    <div class="son">
</div>
CSS部分:
<style>
.father{
    display:flex;
}
.son{
    flex:1;
}
.son::last-child{
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
}
</style>

此时子元素中的隐藏并不能正常生效。此时只需要在子元素中添加width:0即可:

修正的代码:

HTML部分:
<div class="father">
    <div class="son">
    <div class="son">
</div>
CSS部分:
<style>
.father{
    display:flex;
}
.son{
    flex:1;
}
.son::last-child{
    width:0;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
}
</style>