博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CSS实现文本溢出自动截断
阅读量:6637 次
发布时间:2019-06-25

本文共 1873 字,大约阅读时间需要 6 分钟。

hot3.png

 

在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

你可能感兴趣的文章
iOS中你可能没有完全弄清楚的(一)synthesize
查看>>
对空数据页面等公共页面实现的一些思考
查看>>
《XML解析随记》
查看>>
一位老码农的分享:一线程序员该如何面对「中年危机」?
查看>>
java编程思想之注解
查看>>
在 Android 设备上搭建 Web 服务器
查看>>
iOS 网络监控框架 - Reachability 源码解读
查看>>
实战PHP数据结构基础之递归
查看>>
eclipse中如何自动生成构造函数
查看>>
使用Java connector消费ABAP系统的函数
查看>>
【iOS开发】iOS10 Log调试小工具
查看>>
C++ 引用和函数的高级特性
查看>>
code-rhythm:写了个vscode扩展,让代码更有快感
查看>>
机器学习常用算法的分类
查看>>
EM算法学习(二)
查看>>
Android 面试系列 Dn.2---- 广播?
查看>>
用Node.js写爬虫,撸羞羞的图片
查看>>
iOS定时器(时间不在于你拥有多少,而在于你怎样使用)
查看>>
JavaScript 算法之复杂度分析
查看>>
玩转webpack4
查看>>