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

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

输出:

hello
How are you

当前回答

不可能使用相同的HTML结构,你必须有一些东西来区分Hello和How are you。

我建议使用span,然后显示为块(实际上就像<div>)。

P跨度{ 显示:块; } <p><span>hello</span><span>How are you</span></p>

其他回答

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

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

和CSS:

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

关于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.

正常使用<br/>,但是当你不需要它时用display: none隐藏它。

我希望大多数发现这个问题的人都想使用css /响应式设计来决定是否在特定的位置出现换行符。(不要对<br/>有任何个人不满)

虽然不是很明显,但实际上可以对<br/>标记应用display:none来隐藏它,这样就可以与语义br标记一起使用媒体查询。

<div>
  The quick brown fox<br />
  jumps over the lazy dog
</div>
@media screen and (min-width: 20em) {
  br {
    display: none; /* hide the BR tag for wider screens (i.e. disable the line break) */
  }
}

这在响应式设计中非常有用,在这种设计中,您需要在精确的换行处强制将文本分成两行。

jsfiddle例子

在CSS中使用代码

p {
  white-space: pre-line;
}

使用这种CSS, P标签内的每个输入都将是HTML中的一个断行。