文字长度过长显示省略号的样式设置方法众所周知:
h3 {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
然而有一次,我在项目中用到white-space: nowrap的时候,发现它失效了,我的项目是flex布局,宽度自适应的部分,white-space: nowrap撑开了内容区的长度,省略号是显示了,但是父元素的自适应宽度完全不对了。
页面部分布局如下:
<template>
<div class="parent">
<el-col :span="6" v-for="item in list" :key="item.id">
<h3>{{ item.title }}</h3>
......
</el-col>
</div>
</template>
样式如下:
.parent {
flex: auto;
min-height: 100vh;
display: flex;
flex-direction: column;
}
.parent h3 {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
查了一下才知道,原来是因为display:flex影响的,white-space:nowrap会影响flex布局下未设定宽度的元素,所以给设置了display:flex的父元素设置一下min-width: 0;即可解决问题。
.parent {
flex: auto;
min-height: 100vh;
display: flex;
flex-direction: column;
min-width: 0;
}