在web前端开发中,经常要处理的一种情况就是“文本溢出”。比较友好的处理方式是溢出的文本不显示,在末尾加上“…”。实现方式多种多样,可以直接后端程序截断,前端js截断或者CSS实现截断。下面介绍CSS截断的方法。
主要代码有三个属性组成,缺一不可:
overflow: hidden;white-space: nowrap;text-overflow: ellipsis;下面是chrome下的效果:
注意:IE6必须指定宽度。大家可以查看效果。
另外需要指出的是,不同系统的不同浏览器(主要是IE)下,“…”会显示不同的效果(可以在不同浏览器查看)。而且对于文章类的网站,显示大量的“…”也是级差的效果,最佳的方法还是言简意赅的使用一定字数的副标题用于列表。
## 为什么不起作用
`text-overflow:ellipsis; ` only works when the following are true:
1. The element's width must be constrained in px (pixels). Width in % (percentage) won't work.
2. The element must have overflow:hidden and white-space:nowrap set.The reason you're having problems here is because the width of your a element isn't constrained. You do have a width setting, but because the element is set to display:inline (i.e. the default) it is ignoring it, and nothing else is constraining its width either.
You can fix this by doing one of the following:
1. Set the element to `display:inline-block` or `display:block` (probably the former, but depends on your layout needs).
2. Set one of its container elements to display:block and give that element a fixed width or max-width. 3. Set the element to float:left or float:right (probably the former, but again, either should have the same effect as far as the ellipsis is concerned).I'd suggest display:inline-block, since this will have the minimum colateral impact on your layout; it works very much like the display:inline that it's using currently as far as the layout is concerned, but feel free to experiment with the other points as well; I've tried to give as much info as possible to help you understand how these things interract together; a large part of understanding CSS is about understanding how various styles work together.
Hope that helps.
https://stackoverflow.com/questions/17779293/css-text-overflow-ellipsis-not-working