Reputation: 8788
I have a HTML document with some distinct rows of text, is there some decided correct way to display them?
Example:
Here are
some lines
of text
Should I use the <p>
tag for each row, or is there some other/better way to do it?
Examples:
<p>Here are</p>
<p>some lines</p>
<p>of text</p>
or
<p>
Here are <br>
some lines <br>
of text <br>
</p>
Or something completely different?
The CSS & other things isn't really relevant at the moment, I'm just wondering which is the "most correct" way to use.
Upvotes: 30
Views: 94427
Reputation: 96
Using the <pre>
tag is what you want for this:
<pre>
Text in a pre element
is displayed in a fixed-width
font, and it preserves
both spaces and
line breaks
</pre>
pre
stands for "pre-formatted text"
Resources:
https://www.w3schools.com/tags/tag_pre.asp
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre
Upvotes: 4
Reputation: 7130
Or you can try this without tag wrapping each line:
<div style="white-space:pre">
Here are
some lines
of text
</div>
Upvotes: 9
Reputation: 1
If you want to create a multiline paragraph that maintains the line seperation in your code without throwing
s everywhere. Simply use the html tag.
Upvotes: 0
Reputation: 10715
if you have a string with new lines that you want to display for example in a div, you can use white-space: pre-wrap
css style:
.multiline {
white-space: pre-wrap;
}
<div class="multiline">
A multiline text
for demo purpose
</div>
Upvotes: 51
Reputation: 6597
The correct way to do things is using things made for the things you need.
If you want a line break (enter), use <br>
;
If you want to define a paragraph, use <p>
.
Upvotes: 2
Reputation: 723779
The spec makes it very clear that <br>
should never be used unless the line breaks are actually part of the content forming a single unit of text.
As these are distinct rows of text, not a single unit that happens to contain line breaks, they need to be split into separate <p>
elements.
Upvotes: 1
Reputation: 76591
There is no such thing in most correct way, at least according to the current specification of your needs. Yes, you can put them all in separate paragraphs, using the <p></p>
tag or you can separate them via a <br>
tag at every line. You can also use span
s combined with the white-space CSS attribute, so you have a lot of options. To choose the best option for you, you will need to try them out and see what fits your requirements the best.
Upvotes: 0
Reputation: 2202
According to this, the <br>
element is used to insert a line break without starting a new paragraph. Hence you should prefer the second solution over the first.
w3schools comes with a marvelous article about style guides and coding conventions.
Upvotes: 1