如何实现相同的输出没有<br>?

<p>hello <br> How are you </p>

输出:

hello
How are you

当前回答

Vincent Robert和Joey Adams的答案都是正确的。但是,如果您不想更改标记,可以使用javascript插入一个<br />。

在CSS中,不改变标记是无法做到这一点的。

其他回答

我喜欢非常简单的解决方案,这里还有一个:

<p>hello <span>How are you</span></p>

和CSS:

p {
  display: flex;
  flex-direction: column;
}

你可以使用空格:pre;使元素像<pre>一样,保留换行符。例子:

p { 空白:前; } < p >你好 </p>

注意,对于IE,这只适用于IE8+。

有几个选项可以定义空格和换行符的处理。 如果你可以把内容放在<p>标签中,你就很容易得到你想要的东西。

要保留换行符而不保留空格,请使用pre-line(而不是pre),如in:

<style>
 p {
     white-space: pre-line; /* collapse WS, preserve LB */
   }
</style>

<p>hello
How are you</p>

如果需要另一种行为,请选择其中之一(WS=WhiteSpace, LB=LineBreak):

white-space: normal;   /* collapse WS, wrap as necessary, collapse LB */
white-space: nowrap;   /* collapse WS, no wrapping,       collapse LB */
white-space: pre;      /* preserve WS, no wrapping,       preserve LB */
white-space: pre-wrap; /* preserve WS, wrap as necessary, preserve LB */
white-space: inherit;  /* all as parent element */

资料来源:W3学校

我猜您不希望使用断点,因为它总是会断行。对吗?如果是这样,如何在你的文本中添加一个断点<br />,然后给它一个类,如<br class="hidebreak"/>,然后使用媒体查询右上方的大小,你想要它打破隐藏<br />,所以它打破在一个特定的宽度,但保持内联以上的宽度。

HTML:

<p>
The below line breaks at 766px.
</p>

<p>
 This is the line of text<br class="hidebreak"> I want to break.
</p>

CSS:

@media (min-width: 767px) {
  br.hidebreak {display:none;}
}

https://jsfiddle.net/517Design/o71yw5vd/

有关链接列表

其他答案根据具体情况提供了一些添加换行符的好方法。但是需要注意的是:after选择器对于CSS控制链接列表(以及类似的东西)来说是一种更好的方法,原因如下。

下面是一个例子,假设有一个目录:

<style type="text/css">
    .toc a:after{ content: "\a"; white-space: pre; }
</style>

<span class="toc">
    <a href="#a1">Item A1</a> <a href="#a2">Item A2</a>
    <a href="#b1">Item B1</a> <a href="#b2">Item B2</a>
</span>

这是Simon_Weaver的技术,它更简单,更兼容。它没有将风格和内容分开,需要更多的代码,并且可能在某些情况下您希望在事后添加中断。不过这仍然是一个很好的解决方案,尤其是对于老版本的IE。

<style type="text/css">
    .toc br{ display: none; } /* comment out for horizontal links */
</style>

<span class="toc">
    <a href="#a1">Item A1</a><br/> <a href="#a2">Item A2</a><br/>
    <a href="#b1">Item B1</a><br/> <a href="#b2">Item B2</a><br/>
</span>

注意以上解决方案的优点:

No matter the whitespace in the HTML, the output is the same (vs. pre) No extra padding is added to the elements (see NickG's display:block comments) You can easily switch between horizontal and vertical lists of links with some shared CSS without going into every HTML file for a style change No float or clear styles affecting surrounding content The style is separate from the content (vs. <br/>, or pre with hard-coded breaks) This can also work for loose links using a.toc:after and <a class="toc"> You can add multiple breaks and even prefix/suffix text