如何使用 css 按行或字符数限制字符数限制?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13817597/
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
How to restrict character limit by line or # of characters with css?
提问by popsicle
Is there a css property that can do one of the following? But first, let me explain.
是否有可以执行以下操作之一的 css 属性?但首先,让我解释一下。
Imagine a masonry layout where each item is width: 200px; and each would be height: 250px; (this is just an example).
想象一个砌体布局,其中每个项目的宽度为:200px;每个都是 height: 250px; (这只是一个例子)。
In each item, there is a thumbnail and a link, and often times, this link wraps to 2-3 lines, and therefore makes the height of each item different.
在每个项目中,都有一个缩略图和一个链接,并且这个链接经常会被包装成 2-3 行,因此每个项目的高度都不同。
Is there a way I can set a maximum # of characters within a class, or cut off wrapping after a certain # of lines? And perhaps even add some css effect to insert content: "..."; before the line end to show that it was cut off?
有没有办法可以在一个类中设置最大字符数,或者在特定行数后切断换行?甚至可能添加一些 css 效果来插入内容:"..."; 在行结束之前显示它被切断了?
Any help is appreciated.
任何帮助表示赞赏。
Thank you.
谢谢你。
回答by Christoph
You can try text-overflow
, however it has some restrictions, but still might suite you:
您可以尝试text-overflow
,但它有一些限制,但仍然可能适合您:
<div id="container">
This is some short content to demonstrate the css-property
text-overflow
</div>?
#container{
width:100px;
height:50px;
border:1px solid red;
overflow:hidden;
text-overflow:ellipsis;
white-space: nowrap;
}?
回答by Viktor S.
Not characters, but you can set a width of an element in pixels and use text-overflowproperty which should add "...".
不是字符,但您可以以像素为单位设置元素的宽度并使用应添加“...”的文本溢出属性。
Also, you can limit number of lines by setting height of an element to, for instance, 30px and setting line-height CSS property to 15px and add overflow:hidden
. That way you will have exact two lines of text.
此外,您可以通过将元素的高度设置为 30px 并将 line-height CSS 属性设置为 15px 并添加overflow:hidden
. 这样你就会有准确的两行文本。
.twoLines{
height:30px;
line-height:15px;
overflow:hidden;
}