Paragraphs and Line Breaks - HTML Tutorial
In Tinkering, you saw that browsers ignore extra spaces and line breaks in your code. So how do you split text into separate paragraphs? With HTML elements.
The Problem
Here's some text written over several lines:
<body>
Welcome to the Corner Cafe.
We serve fresh coffee, homemade cakes and the best
pancakes in town.
Come and visit us any day of the week.
</body>
In the browser, it all runs together into one block:
Welcome to the Corner Cafe. We serve fresh coffee, homemade cakes and the best pancakes in town. Come and visit us any day of the week.
The p Element
To create a paragraph, wrap the text in a p element:
<p>Welcome to the Corner Cafe.</p>
<p>We serve fresh coffee, homemade cakes and the best
pancakes in town.</p>
<p>Come and visit us any day of the week.</p>
Now each paragraph appears as its own block, with space above and below it. The line break in the middle of the second paragraph is still ignored, so the browser wraps the text to fit the window.
Always close your paragraphs with </p>. Browsers can often guess where an unclosed paragraph ends, but not always, and closing every paragraph keeps your code clear and predictable.
Caution
Don't add empty paragraphs (<p></p>) to create extra space. Spacing is a job for CSS, which you'll learn about in Margins and Padding.
The br Element
Sometimes you need a line break inside a paragraph, where the lines belong together. Addresses and poems are good examples. For this, use the br element:
<p>
Corner Cafe<br>
12 Main Street<br>
Springfield
</p>
The br element is a void element, so it has no closing tag. Use it only when the line break is part of the content itself. If you find yourself using several br elements in a row to push things apart, you probably want separate paragraphs or some CSS spacing instead.
The hr Element
The hr element marks a change of topic between paragraphs, such as a scene change in a story. Browsers display it as a horizontal line, which you can restyle with CSS.
<p>...and that was the end of the first day.</p>
<hr>
<p>The next morning began with rain.</p>