CSS实现文本溢出自动截断

本文介绍了一种常见的Web前端处理方式——当文本溢出时,在末尾使用省略号代替多余的内容。通过设置CSS样式`overflow:hidden; white-space:nowrap; text-overflow:ellipsis;`可以达到此效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

在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

转载于:https://my.oschina.net/uniquejava/blog/505510

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值