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

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

输出:

hello
How are you

当前回答

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

显示:块;

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

其他回答

这适用于Chrome浏览器:

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

一个现代而简单的解决方案是这样设置宽度:

宽度:min-content;

这个CSS规则主要适用于文本内容,但不仅限于: https://developer.mozilla.org/en-US/docs/Web/CSS/min-content

p { 保证金:20 px; 颜色:# 222; font-family:'世纪哥特式',sans-serif; 边框:2px虚线灰色; 填充:3 px; } .max { 宽度:max-content; } .min { 宽度:min-content; } <!DOCTYPE html > < html lang =“en”> <头/ > <身体> <p class="max">最大宽度</p> <p class="min">最小可用宽度</p> < /身体> < / html >

在我的例子中,我需要一个输入按钮前面有一个换行符。 我应用如下样式的按钮,它工作:

clear:both;

正常使用<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例子

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

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