Html 截断div内的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15405817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Truncating text inside a div
提问by ?yvind Br?then
I have some dynamic text (comes from a database) and I need to fit into a div
我有一些动态文本(来自数据库),我需要适应 div
My div
has a fixed size. However, when the text becomes too long, it breaks into two lines. I would like to put three dots at the end of longer texts to make them fit inside a single line.
我的div
有固定尺寸。但是,当文本变得太长时,它会分成两行。我想在较长文本的末尾放置三个点,以使它们适合一行。
For example: My really long text
becomes My really lo...
例如:My really long text
变成My really lo...
I have committed several attempts, but basically all of them depend on counting characters. That is, whatsoever, not really fortunate, for characters do not have a fixed width. For example, a capital W
is much wider than an small i
我进行了几次尝试,但基本上所有尝试都依赖于计数字符。也就是说,无论如何,并不是很幸运,因为字符没有固定的宽度。例如,一个资本W
比一个小i
Therefore, I encounter two main problems with the character-counting approach:
因此,我在使用字符计数方法时遇到了两个主要问题:
If the text has many narrow characters, it gets cut and appended with ..., even if the text would actually fit on one line afore trimmed.
When the text contains many wide characters, it ends up on two lines even after I cut it to the maximum number of characters and append the dots.
如果文本有许多窄字符,它会被剪切并附加...,即使文本在修剪前实际上适合一行。
当文本包含许多宽字符时,即使我将其剪切到最大字符数并附加点,它也会以两行结尾。
Is there any solution here (JavaScript or CSS) that takes the actual width of the text into consideration, and not the number of characters?
这里是否有任何解决方案(JavaScript 或 CSS)考虑文本的实际宽度,而不是字符数?
回答by James Coyle
Use these styles:
使用这些样式:
white-space: nowrap; /*keep text on one line */
overflow: hidden; /*prevent text from being shown outside the border */
text-overflow: ellipsis; /*cut off text with an ellipsis*/
回答by Ryan McDonough
回答by Shouvik
回答by Kev
You should look at css ellipsis : http://www.w3schools.com/cssref/css3_pr_text-overflow.asp
你应该看看 css 省略号:http: //www.w3schools.com/cssref/css3_pr_text-overflow.asp