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

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

输出:

hello
How are you

当前回答

<pre> <---------------------------------------
lorem ipsum
lorem ipsum
lorem ipsum
lorem ipsum
lorem ipsum
</pre> <--------------------------------------

OR

<div style="white-space:pre">  <-----------------------------------
lorem ipsum
lorem ipsum
lorem ipsum
lorem ipsum
lorem ipsum
</div>                         <-----------------------------------

来源:https://stackoverflow.com/a/36191199/2377343

其他回答

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

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

代码可以是:

<div class="text-class"><span>hello</span><span>How are you</span></div>

CSS将是:

.text-class {
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  align-items: center;
}

关于css技巧,Chris coyer测试了很多选项,最后一个非常简洁的选项是使用display:table,每个选项都有自己的问题,当你在span上使用background-color时,你会发现!

身体{ 填充:20 px; font-family: 'Open Sans', Sans -serif; } h1 { 粗细:300; 字体大小:24 px; 行高:1.6; 背景:# eee; 填充:20 px; 边框:5px 0 25px 0; text-align:中心; } H1跨度{ 颜色:白色; 粗细:900; } H1跨度{ 背景:黑色; 填充:1px 8px; 显示:表; 保证金:汽车; } < h1类= " 1 " > 稍后休息 < span > 在此之前 < / span > < / h1 >

在这里你可以看到codeen上的所有其他选项:

注入换行符

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

显示:块;

块级元素之后的非浮动元素将在下一行出现。许多元素,如<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.

CSS中的“\a”命令生成一个回车。这是CSS,不是HTML,所以它应该更接近你想要的:没有额外的标记。

在一个blockquote中,下面的例子同时显示标题和源链接,并用回车符("\a")分隔两者:

blockquote[title][cite]:after {
  content:attr(title)"\a"attr(cite)
}