Html 将 div 高度限制为里面的两行文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17242209/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:21:09  来源:igfitidea点击:

Limiting a div height to two lines of text inside it?

htmlcss

提问by Flood Gravemind

As the question says how to limit a div's height to one/two/n lines of the text inside it?

正如问题所说,如何将 div 的高度限制为其中一行/两/n 行文本?

回答by Daniel Gimenez

div {
    height: 1em; // that's one line, 2em for 2 lines, etc...
    line-height: 1em; // the height of one text line
    overflow: hidden;
}

This will display a div with a height the size of the current font size, and any overflow is clipped. As long as line-height and height are equal there will be one line of text. The proportion of height/line-height determines the number of lines displayed.

这将显示一个高度为当前字体大小的 div,并且任何溢出都会被裁剪。只要 line-height 和 height 相等,就会有一行文本。高度/行高的比例决定了显示的行数。

回答by ScottS

The emunit adjusts by font-size, and line-heightproportions are also based on that. So those are what you want to be using for "fixing" height.

em单元的调整font-size,并且line-height比例也基于这一点。所以这些就是你想用来“固定”高度的东西。

You want either this:

你想要这个:

div {
    height: 2.2em;
    line-height: 1.1;
    overflow: auto;
}

Example Fiddle.

示例小提琴。

Or if you want it to potentially reduce to 1 line, then use this:

或者,如果您希望它可能减少到 1 行,请使用以下命令:

div {
    max-height: 1.1em;
    line-height: 1.1;
    overflow: auto;
}

Example Fiddle.

示例小提琴。