How to line-break from css, without using <br />?
output:
hello How are you
code:
<p>hello <br> How are you </p>
How to achieve same output without <br>
?
Impossible with the same HTML structure, you must have something to distinguish between Hello
and How are you
.
I suggest using span
s that you will then display as blocks (just like a <div>
actually).
p span {
display: block;
}
<p><span>hello</span><span>How are you</span></p>
You can use white-space: pre;
to make elements act like <pre>
, which preserves newlines. Example:
p {
white-space: pre;
}
<p>hello
How are you</p>
Note for IE that this only works in IE8+.
Use <br/>
as normal, but hide it with display: none
when you don't want it.
I would expect most people finding this question want to use css / responsive design to decide whether or not a line-break appears in a specific place. (and don't have anything personal against <br/>
)
While not immediately obvious, you can actually apply display:none
to a <br/>
tag to hide it, which enables the use of media queries in tandem with semantic BR tags.
<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) */
}
}
This is useful in responsive design where you need to force text into two lines at an exact break.
jsfiddle example
There are several options for defining the handling of white spaces and line breaks.
If one can put the content in e.g. a <p>
tag it is pretty easy to get whatever one wants.
For preserving line breaks but not white spaces use pre-line
(not pre
) like in:
<style>
p {
white-space: pre-line; /* collapse WS, preserve LB */
}
</style>
<p>hello
How are you</p>
If another behavior is wanted choose among one of these (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 */
SOURCE: W3 Schools