如何实现相同的输出没有<br>?
<p>hello <br> How are you </p>
输出:
hello How are you
如何实现相同的输出没有<br>?
<p>hello <br> How are you </p>
输出:
hello How are you
当前回答
有关链接列表
其他答案根据具体情况提供了一些添加换行符的好方法。但是需要注意的是: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
其他回答
一个现代而简单的解决方案是这样设置宽度:
宽度: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 >
基于之前所说的,这是一个工作的纯CSS解决方案。
<style>
span {
display: inline;
}
span:before {
content: "\a ";
white-space: pre;
}
</style>
<p>
First line of text. <span>Next line.</span>
</p>
你可以使用空格:pre;使元素像<pre>一样,保留换行符。例子:
p { 空白:前; } < p >你好 </p>
注意,对于IE,这只适用于IE8+。
下面是一个糟糕问题的糟糕解决方案,但它确实符合概要:
p {
width : 12ex;
}
p:before {
content: ".";
float: right;
padding-left: 6ex;
visibility: hidden;
}
要使元素在后面有换行符,为它赋值:
显示:块;
块级元素之后的非浮动元素将在下一行出现。许多元素,如<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.