当内容超过宽度时,禁止换行,使用省略号...代替溢出的内容,一般这样的需求都会经常遇到。
使用css的text-overflow: ellipsis属性,可设置省略号,需要注意的是:1. 如果设置了display: flex,则换行无效。2. 一定要设置宽度
根据标签层级不同,设置省略号的css样式也不同,下面分为几种场景:
场景1:普通场景
代码如下:
// html <div class="content">文本文本文本文本文本文本</div> // css .content { width: 200px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
场景2:
父级使用display: flex,那么子级.text设置了flex: 1就是设置了一个宽度,换行有效。
代码如下:
// html <div class="name"> <div class="label">姓名</div> <div class="text">文本文本文本文本文本文本文本文本文本文本文本文本</div> </div> // css .name { display: flex; .label { width: 140px; } .text { flex: 1; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } }
场景3:
.text里面有一层子级元素.text1
如果在.text设置换行样式,是无效的。此时.text相当于.text1的父级了,所以.text只需要设置宽度,.text1设置换行样式。
方式1:若确定了.label的宽度,则设置父级.text的宽度,如:width: calc(100% - 140px);
方式2:若不确定.label的宽度,则设置父级.text的flex和overflow即可:如:flex: 1; overflow: hidden;
子级.text1直接设置换行样式即可。
代码如下:
// html <div class="name"> <div class="label">姓名</view> <div class="text"><div class="text1">文本文本文本文本文本文本文本文本文本文本</div></div> </div> // css .name { display: flex; .label { width: 140px; } .text { // 方式1,使用width,前提是确定了.label的宽度 // width: calc(100% - 140px); // 方式2:flex和overflow同时设置,.label的宽度不确定(推荐) flex: 1; overflow: hidden; .text1 { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } } }
场景4(场景3的升级版):
在情境3的基础上,还有一层外层包裹着,这通常是一个组件,就需要使用到js改变内联样式,方式同情景3的方式2
代码如下:
// html // 父组件
<div class="form" style="display: flex;">
<div class="form-label" style="width: 140px;"></div> <div class="form-content" style="flex: 1;"> <child /> </div>
</div> // 子组件child <div class="name" ref="nameRef"> <div class="text">文本文本文本文本文本文本文本文本文本文本</div> </div> // script import { ref } from 'vue' let nameRef = ref() onMounted(() => { nameRef.value.parentNode.style.overflow = 'hidden' }) // css .name { .text { text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } }