CSS 如何为固定数量的文本行设置元素高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3675623/
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 set element height for a fixed number of lines of text
提问by Tom
Given some text that occupies about 10 rows, how can I resize its container to only show the first 3 rows and hide the others? Apparently this works, but I think it is not reliable:
给定一些占据大约 10 行的文本,如何调整其容器的大小以仅显示前 3 行并隐藏其他行?显然这是有效的,但我认为它不可靠:
.container {
height: 7.5ex; /* 2.5ex for each visible line */
overflow: hidden;
}
Can I rely on the fact that height of one row = 2.5ex
or is that just a coincidence in the browsers I am using to test?
我可以依赖这样一个事实吗,height of one row = 2.5ex
或者这只是我用来测试的浏览器的巧合?
回答by irishbuzz
回答by Johan
The ex unit is the font x-height (height of its x character). I would not use this here. You should use the em unit. This is the actual font-height. The font-height is defined by setting the line-height property. So:
ex 单位是字体 x 高度(其 x 字符的高度)。我不会在这里使用它。您应该使用 em 单位。这是实际的字体高度。font-height 是通过设置 line-height 属性来定义的。所以:
.container {
height: 3em; /* 1em for each visible line */
overflow: hidden;
}
Here is some more info on CSS length units: http://www.w3.org/TR/CSS21/syndata.html#length-units
以下是有关 CSS 长度单位的更多信息:http: //www.w3.org/TR/CSS21/syndata.html#length-units
回答by Davide
you can set the line height of a text and with it knows the exact height of each row and set desired height of your container, simply doing this:
您可以设置文本的行高,并知道每行的确切高度并设置容器的所需高度,只需执行以下操作:
.container {
line-height:25px;
height:75px;
overflow:hidden;
}
Now everything works rightly :)
现在一切正常:)
回答by Bit68
You can use the webkit property line-clamp
您可以使用 webkit 属性 line-clamp
.container {
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
It doesn't work on all browsers, but hopefully it will one day.
它不适用于所有浏览器,但希望有一天它会。