HTML Paragraphs

HTML
CSS
C#
SQL

HTML Paragraphs

A paragraph in HTML is a block of text that typically contains sentences and displays as a distinct block of content on a web page.
Paragraphs are essential for organizing text content in a readable format.

Defining a Paragraph

  • The HTML <p> element is used to define a paragraph.
  • Paragraphs always start on a new line and browsers add some space (margin) before and after each paragraph to separate them from other content.

Syntax

A paragraph element is written with an opening <p> tag and a closing </p> tag.

Example

Automatic Formatting

  • Browsers automatically handle the formatting of paragraphs, including line breaks and spacing.
  • Extra spaces and line breaks in the HTML code are ignored by the browser, and the text is displayed as a single block.

Example

<p>
This paragraph contains a lot of lines in the source code,
but the browser ignores it and displays it as a single line.
</p>

<p>
This paragraph contains a lot of spaces in the source code,
but the browser ignores it and displays it with single spaces.
</p>

Horizontal Rules

  • The <hr> element is used to create a horizontal line that can visually separate sections of content.
  • It is often used to indicate a thematic break or a change in topic.
  • The <hr> tag is an empty tag, which means it does not have a closing tag.

Example

<h1>This is heading 1</h1>
<p>This is some text.</p>
<hr>
<h2>This is heading 2</h2>
<p>This is some other text.</p>
<hr>

Creating Line Breaks

  • The <br> element is used to insert a line break within a paragraph or any block of text.
  • It allows you to break the text into a new line without starting a new paragraph.
  • The <br> tag is an empty tag and does not have a closing tag.

Example

<p>This is <br> a paragraph <br> with line breaks.</p>

Handling Preformatted Text

The Poem Problem

When you want to display text with preserved spaces and line breaks (such as a poem), using the <p> element will not work as it displays the text in a single block.

Example

<p>
My Bonnie lies over the ocean.
My Bonnie lies over the sea.
My Bonnie lies over the ocean.
Oh, bring back my Bonnie to me.
</p>

Solution: The <pre> Elements

  • The <pre> element is used for preformatted text.
  • Text inside an <pre> element is displayed in a fixed-width font (usually Courier), and both spaces and line breaks are preserved.
  • This is ideal for displaying code, poems, or any text where formatting is important.

Example

<pre>
My Bonnie lies over the ocean.
My Bonnie lies over the sea.
My Bonnie lies over the ocean.
Oh, bring back my Bonnie to me.
</pre>

YouTube Reference :