如何阻止文本占用超过 1 行?
是否有自动换行或任何其他属性可以阻止文本换行? 我有一个高度和overflow:hidden
,但文本仍然中断。
需要在 CSS3 之前的所有浏览器中工作。
Is there a word-wrap or any other attribute that stops text from wrapping? I have a height, and overflow:hidden
, and the text still breaks.
Needs to work in all browsers, before CSS3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
注意:这只适用于块元素。 如果您需要对表格单元格执行此操作(例如),您需要在表格单元格内放置一个 div,因为表格单元格具有显示表格单元格而不是块。从 CSS3 开始,表格单元格也支持此操作。
Note: this only works on block elements. If you need to do this to table cells (for example) you need to put a div inside the table cell as table cells have display table-cell not block.As of CSS3, this is supported for table cells as well.
您可以使用 CSS
white-space
属性来实现这一点。You can use the CSS
white-space
property to achieve this.使用
text-overflow: ellipsis
将在最后添加 ...。Using
text-overflow: ellipsis
will add the ... at the last.明确地说,这可以很好地处理段落、标题等。您只需指定
display: block
即可。例如:
Just to be crystal clear, this works nicely with paragraphs, headers, etc. You just need to specify
display: block
.For instance:
有时使用
代替空格会起作用。 但显然它也有缺点。
Sometimes using
instead of spaces will work. Clearly it has drawbacks, though.
如果要防止文本换行并确保其在容器内保持在单行上,则可以使用值为
nowrap
的white-space
属性。 这也适用于较旧的浏览器。下面是一个示例:
将
.container
替换为实际容器元素的类或 ID。 这将确保文本不会换行并保持在一行上。If you want to prevent text from wrapping and ensure it stays on a single line within a container, you can use the
white-space
property with the valuenowrap
. This works in older browsers as well.Here's an example:
Replace
.container
with the class or ID of your actual container element. This will make sure the text doesn't wrap and stays on a single line.目前正在为此目的直接引入相当新的
text-wrap
CSS 属性,以将文本破坏与空白折叠分开。 要使内容溢出容器而不是创建新行,请将其与nowrap
值一起使用:有关更多详细信息,请在此处阅读完整文档:
https://developer.mozilla.org/en-US/ docs/Web/CSS/text-wrap
截至撰写本答案时,浏览器采用率目前为 71.33%:
https://caniuse.com/?search=text-wrap%3A%20nowrap< /a>
The fairly new
text-wrap
CSS property is currently being introduced directly for this purpose, to separate text breaking from white space collapsing. To make the content overflow the container instead of creating a new line, use it with thenowrap
value:For more details, read the full documentation here:
https://developer.mozilla.org/en-US/docs/Web/CSS/text-wrap
As of writing this answer, browser adoption is currently at 71.33%:
https://caniuse.com/?search=text-wrap%3A%20nowrap