将一行文本保持为一行-将整行换行或根本不换行


72

我想将一行文本保持在一起,以便整行都向下一行或根本不行

可以接受

How do I wrap this line of text - asked by Peter 2 days ago

可以接受

How do I wrap this line of text 
- asked by Peter 2 days ago

不能接受的

How do I wrap this line of text - asked by Peter 
2 days ago

这在CSS中可以实现吗?


您的行如何用标记表示?您是否只是在假设新行,因为其中包含连字符?
DoctorMick 2011年

@DoctorMick-没有换行符的假设,并且标记完全可以接受任何内容-@Gus的答案对我来说很有帮助-ty
Peter Nixey

Answers:


149

您可以white-space: nowrap;用来定义此行为:

// HTML:

.nowrap {
  white-space: nowrap ;
}
<p>
      <span class="nowrap">How do I wrap this line of text</span>
      <span class="nowrap">- asked by Peter 2 days ago</span>
    </p>

// CSS:
.nowrap {
  white-space: nowrap ;
}

8
除非跨度之内的文本量无法在一行上显示,否则它将很好地起作用。在小型/移动屏幕和自适应网站上需要考虑的事情。
Paul Hiles 2013年

@PaulHiles,您可以使用媒体断点检测器删除较小屏幕上的nowrap
Peter Nixey

1

您还可以使用不间断的空格(&nbsp;)代替空格,以使它们被迫保持在一起。

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

正如上面提到的Paul Hiles所述,这也很好用,除非无法在一行上显示大量文本,在这种情况下,该文本会被切断。
Dov Miller
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.