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

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

输出:

hello
How are you

当前回答

有几个选项可以定义空格和换行符的处理。 如果你可以把内容放在<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学校

其他回答

也许有人会有和我一样的问题:

我在一个带有display: flex的元素中,所以我必须使用flex-direction: column。

例如,您可以添加大量的填充和强制文本拆分到新行

p {
  padding-right: 50%;
}

对我来说,在响应式设计的情况下工作得很好,只有在一定的宽度范围内,文本才需要被分割。

这适用于Chrome浏览器:

p::after {
  content: "-";
  color: transparent;
  display: block;
}

要使元素在后面有换行符,为它赋值:

显示:块;

块级元素之后的非浮动元素将在下一行出现。许多元素,如<p>和<div>已经是块级元素,所以您可以只使用它们。

But while this is good to know, this really depends more on the context of your content. In your example, you would not want to use CSS to force a line break. The <br /> is appropriate because semantically the p tag is the the most appropriate for the text you are displaying. More markup just to hang CSS off it is unnecessary. Technically it's not exactly a paragraph, but there is no <greeting> tag, so use what you have. Describing your content well with HTMl is way more important - after you have that then figure out how to make it look pretty.

如果这能帮助到某人…

你可以这样做:

<p>This is an <a class="on-new-line">inline link</a>?</p>

用这个css:

a.on-new-line:before { 
  content: '&nbsp;'; 
  font-size:0; 
  display:block;
  line-height:0;
}