Text Formatting and Headings in HTML

Course: Python Full Stack Web Developer Course - Week 4

Location: lectures/week04/html_text_headings.html

Introduction to Text in HTML

Text is the foundation of the web. While modern websites incorporate various media types, text remains the primary medium for conveying information. HTML provides a rich set of elements for formatting text, creating headings, and organizing content in a way that's both visually appealing and semantically meaningful.

In this tutorial, we'll explore how to structure and format text in HTML, focusing on headings, paragraphs, and various text formatting elements. Think of these elements as the typographical tools in your web development toolkit – each with specific purposes and effects.

HTML Headings

Headings in HTML are like the chapter titles, section headers, and subheadings in a book. They structure your content hierarchically and help readers scan and understand your page's organization.

The Six Heading Levels

HTML provides six levels of headings, from <h1> (most important) to <h6> (least important). Think of them as an outline structure, similar to how you might organize a research paper or book:

<h1>Main Title (typically one per page)</h1>
<h2>Major Section</h2>
<h3>Subsection</h3>
<h4>Sub-subsection</h4>
<h5>Minor heading</h5>
<h6>Smallest heading</h6>

By default, browsers display these headings in decreasing font sizes, with <h1> being the largest. However, remember that their primary purpose is to establish a content hierarchy, not to control the visual presentation (which is better handled with CSS).

Why Headings Matter

Headings are crucial for several reasons:

  • Accessibility: Screen readers use headings to help visually impaired users navigate your content. Think of headings as audible signposts for these users.
  • SEO: Search engines use headings to understand your content structure and what's most important. They're like chapter titles in a book's table of contents that help search engines catalog your page.
  • Readability: Headings break up text into scannable sections, making your content more digestible. This is like how newspaper headlines and section headers help readers quickly find information.
  • Document Outline: Headings create a hierarchical document outline, which helps organize your content logically.

Heading Best Practices

  • Use only one <h1> per page: Think of <h1> as the title of your document. Having multiple <h1> elements is like having multiple titles for the same book.
  • Follow a logical hierarchy: Don't skip heading levels (e.g., don't go from <h2> to <h4> without using <h3>). This is like maintaining a proper outline structure in a document.
  • Be descriptive but concise: Headings should clearly indicate what the following content is about, like signposts on a road.
  • Don't use headings just for styling: If you want larger or bold text, use CSS rather than misusing heading elements.

Real-World Heading Example

Here's how headings might be used in a simple article:

<article>
    <h1>Understanding Climate Change</h1>
    
    <p>Introduction paragraph explaining the concept...</p>
    
    <h2>Causes of Climate Change</h2>
    <p>Explanation of causes...</p>
    
    <h3>Greenhouse Gas Emissions</h3>
    <p>Details about greenhouse gases...</p>
    
    <h3>Deforestation</h3>
    <p>Information about deforestation impact...</p>
    
    <h2>Effects of Climate Change</h2>
    <p>Overview of effects...</p>
    
    <h3>Rising Sea Levels</h3>
    <p>Details about sea level rise...</p>
    
    <h3>Extreme Weather Events</h3>
    <p>Information about increased storms, droughts, etc...</p>
    
    <h2>Solutions and Mitigation Strategies</h2>
    <p>Overview of solutions...</p>
</article>

Notice how this creates a clear hierarchy: main title, major sections, and subsections. This structure helps both human readers and machines understand the content organization.

Paragraphs

Paragraphs are the fundamental building blocks of text content. In HTML, paragraphs are created using the <p> element.

Basic Paragraph Usage

<p>This is a paragraph of text. It can contain multiple sentences and even span multiple lines in your HTML code, but it will be rendered as a continuous block of text.</p>
<p>This is a second paragraph. Notice how browsers automatically add space between paragraphs.</p>

In HTML, paragraph elements automatically create a new block of text with space before and after it. This is similar to how paragraphs are separated in printed books and documents.

Whitespace and Line Breaks

HTML ignores extra whitespace and line breaks within paragraphs. This is called "whitespace collapsing" and means multiple spaces, tabs, and line breaks in your HTML code are treated as a single space when displayed in the browser.

<p>This paragraph has      multiple    spaces
    and line breaks in the HTML code,
but the browser will collapse them into a single space.</p>

If you want to force a line break within a paragraph, you can use the <br> element:

<p>This is the first line.<br>
This text will appear on a new line.</p>

Use <br> sparingly and only when a line break is semantically meaningful, such as in addresses or poetry. For most spacing and layout needs, CSS is more appropriate.

Paragraph Styling Tips

  • Keep paragraphs focused: Each paragraph should represent a single thought or idea, like in traditional writing.
  • Consider line length: Very long lines of text are difficult to read. Later, you'll learn how to control this with CSS.
  • Use appropriate spacing: The default spacing between paragraphs can be adjusted with CSS, but generally provides good readability.
  • Think about text alignment: Left-aligned text (the default) is generally most readable for body content in languages that read left-to-right.

Text Formatting Elements

HTML provides various elements for formatting text within paragraphs and other containers. These elements allow you to emphasize words, mark important text, display code, and more.

Semantic Formatting Elements

Semantic elements provide meaning to the text they enclose, not just visual formatting. Using these is like the difference between using proper punctuation marks versus just making text bigger or smaller arbitrarily. Semantic elements communicate the purpose of the text.

Element Description Example Use Case
<strong> Strong importance, urgency, or seriousness <p>Read the <strong>warning label</strong> before proceeding.</p> Warnings, key points, critical information
<em> Emphasized text, stress or change in tone <p>I <em>really</em> need you to listen.</p> Words you would stress when speaking, contrasts
<mark> Marked or highlighted text <p>Pay attention to the <mark>highlighted</mark> terms.</p> Highlighting key terms, search results
<cite> Title of a creative work <p>My favorite book is <cite>To Kill a Mockingbird</cite>.</p> Book titles, movie names, song titles
<q> Short inline quotation <p>She said, <q>This meeting is important</q> before leaving.</p> Brief quotes within a paragraph
<blockquote> Extended quotation (block-level) <blockquote><p>Four score and seven years ago...</p></blockquote> Longer quotes, testimonials
<abbr> Abbreviation with optional title <p><abbr title="World Health Organization">WHO</abbr> guidelines...</p> Acronyms and abbreviations with explanations
<dfn> Definition of a term <p><dfn>HTML</dfn> is a markup language used for creating web pages.</p> First instance of technical terms

Presentational Elements

While semantic elements are preferred when they convey the right meaning, HTML also includes elements that primarily affect presentation. These should be used when there's no semantic alternative for what you're trying to express.

Element Description Example Use Case
<b> Bold text without strong importance <p>The concert starts at <b>8:00 PM</b>.</p> Keywords, product names, text that should stand out without extra importance
<i> Italic text without emphasis <p>The ship was named <i>Titanic</i>.</p> Foreign terms, technical terms, thoughts
<small> Smaller text <p>Regular price $100 <small>(plus tax)</small></p> Fine print, copyright notices, legal text, side comments
<sub> Subscript text <p>Water is H<sub>2</sub>O.</p> Chemical formulas, footnotes
<sup> Superscript text <p>10<sup>2</sup> equals 100.</p> Mathematical exponents, footnote markers

Semantic vs. Presentational: Making the Right Choice

When deciding which element to use, consider the meaning you want to convey:

For emphasis:

  • Use <strong> when the text has strong importance, seriousness, or urgency
  • Use <em> when emphasizing a term with stress that changes the meaning
  • Use <b> when text should stand out without implying extra importance
  • Use <i> when text represents an alternate voice or mood
<p><strong>Warning:</strong> This ride has height restrictions.</p>
<p>I <em>need</em> to finish this today, not tomorrow.</p>
<p>Please enter your <b>username</b> to continue.</p>
<p>The character thought, <i>What if I don't make it in time?</i></p>

Text Editing Elements

HTML includes elements that indicate text has been edited:

Element Description Example
<ins> Inserted text <p>The meeting is on <del>Tuesday</del> <ins>Wednesday</ins>.</p>
<del> Deleted text <p>We need <del>five</del> <ins>ten</ins> volunteers.</p>

These elements are useful for showing document changes, revisions, or corrections. They're like the "track changes" feature in word processors.

Code and Technical Text Elements

For displaying code and technical content, HTML provides specialized elements:

Element Description Example Use Case
<code> Computer code snippets <p>The <code>print()</code> function displays output.</p> Inline code references
<pre> Preformatted text (preserves spaces and line breaks) <pre> def greet(): print("Hello!") </pre> Code blocks, ASCII art, preserving formatting
<kbd> Keyboard input <p>Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy.</p> Keyboard instructions, commands
<samp> Sample output <p>The program returned: <samp>Error 404: File not found</samp></p> Program output, system messages
<var> Variables <p>The area is calculated as <var>length</var> × <var>width</var>.</p> Mathematical variables, programming variables

These elements are particularly useful when creating technical documentation, tutorials, or displaying code examples.

Combined Example for Code Documentation:

<h2>Using the Greeting Function</h2>
<p>The <code>greet()</code> function accepts a <var>name</var> parameter:</p>

<pre><code>def greet(name="World"):
    print(f"Hello, {name}!")</code></pre>

<p>When you call <code>greet("John")</code>, the output will be:</p>
<samp>Hello, John!</samp>

<p>Try it yourself by typing <kbd>python3 greeting.py</kbd> in your terminal.</p>

Special Characters and Entities

HTML uses certain characters for its syntax, which means you need special codes (called entities) to display them as literal characters in your content.

Common HTML Entities

Character Entity Name Entity Number Description
< &lt; &#60; Less than sign
> &gt; &#62; Greater than sign
& &amp; &#38; Ampersand
" &quot; &#34; Double quotation mark
' &apos; &#39; Single quotation mark (apostrophe)
© &copy; &#169; Copyright symbol
® &reg; &#174; Registered trademark
&trade; &#8482; Trademark symbol
  &nbsp; &#160; Non-breaking space
&mdash; &#8212; Em dash
&ndash; &#8211; En dash

When to Use Entities

  • Always use entities for: < (&lt;), > (&gt;), and & (&amp;) when you want them to appear as literal characters in your content.
  • Use entities for special symbols not available on standard keyboards: ©, ®, ™, etc.
  • Use &nbsp; for non-breaking spaces, which prevent line breaks at specific points.

Example with Special Characters:

<p>To create an HTML element, you use &lt;tagname&gt; with content and &lt;/tagname&gt;.</p>
<p>Some HTML entities include &amp;copy; for the copyright symbol (&copy;) and &amp;trade; for trademark (&trade;).</p>
<p>Please don't break&nbsp;this&nbsp;phrase across lines.</p>

Practical Applications and Examples

Let's see how these text formatting and heading elements work together in real-world examples.

Example 1: News Article

<article>
    <h1>Scientists Discover New Species in Amazon Rainforest</h1>
    
    <p><strong>MANAUS, BRAZIL</strong> &mdash; A team of researchers has discovered a previously unknown species of frog in the Amazon rainforest, according to a study published on <time datetime="2025-04-15">April 15, 2025</time>.</p>
    
    <p>The newly identified amphibian, named <i>Dendrobates azureus amazonicus</i>, is characterized by its vibrant blue coloration and unique vocalizations. Lead researcher Dr. Maria Santos described the discovery as <q>a remarkable finding that highlights the incredible biodiversity that remains to be documented in the Amazon basin.</q></p>
    
    <h2>Significant Characteristics</h2>
    
    <p>The new species exhibits several notable features:</p>
    
    <ul>
        <li>Electric blue skin with black spots</li>
        <li>Approximately 2.5 cm in length</li>
        <li>Distinctive three-pulse call pattern</li>
        <li>Toxic skin secretions</li>
    </ul>
    
    <p><mark>Conservation status: Potentially endangered</mark> due to habitat loss.</p>
    
    <h2>Implications for Conservation</h2>
    
    <p>This discovery underscores the importance of preserving the Amazon rainforest, which continues to face threats from deforestation and climate change. The research team estimates that the species' habitat has decreased by <del>15%</del> <ins>25%</ins> in the last decade alone.</p>
    
    <blockquote>
        <p>Every new species we discover in threatened habitats adds urgency to conservation efforts. This small frog represents not just a scientific discovery, but a reminder of what we stand to lose.</p>
        <cite>Dr. Carlos Mendez, Conservation Biologist</cite>
    </blockquote>
    
    <p><small>&copy; 2025 Science Today. All rights reserved.</small></p>
</article>

Example 2: Product Description

<section class="product">
    <h2>Ultra HD Smart TV &ndash; 65" Model X2000</h2>
    
    <p class="price"><strong>$1,299.99</strong> <small>(Was $1,499.99)</small></p>
    
    <p class="availability"><mark>In Stock</mark> &ndash; Free delivery available</p>
    
    <h3>Product Highlights</h3>
    
    <ul>
        <li><b>Resolution:</b> 4K Ultra HD (3840 &times; 2160)</li>
        <li><b>Screen Size:</b> 65" (diagonal)</li>
        <li><b>HDR:</b> Dolby Vision<sup>&reg;</sup> and HDR10</li>
        <li><b>Smart Features:</b> Built-in voice assistant, streaming apps</li>
        <li><b>Connectivity:</b> 4 &times; HDMI 2.1, Wi-Fi 6, Bluetooth 5.0</li>
    </ul>
    
    <h3>Product Description</h3>
    
    <p>Experience stunning picture quality with the X2000 Smart TV. Featuring our <em>latest</em> quantum dot technology, this TV delivers vibrant colors and deep blacks for an immersive viewing experience.</p>
    
    <p>The <i>TruMotion 120</i><sup>&trade;</sup> technology reduces motion blur, making it <strong>perfect for sports and action movies</strong>. With the built-in AI processor, standard definition content is automatically upscaled to near-4K quality.</p>
    
    <h3>Technical Specifications</h3>
    
    <p>Power consumption: 125W (typical), <0.5W (standby)<br>
    Dimensions (W&times;H&times;D): 57.1" &times; 32.9" &times; 2.4"<br>
    Weight: 58 lbs</p>
    
    <p class="warranty"><small>2-year manufacturer warranty included. Extended warranty available for purchase.</small></p>
</section>

Example 3: Technical Documentation

<section class="documentation">
    <h2>Python String Formatting</h2>
    
    <p>Python provides several methods for formatting strings. This guide covers the most common approaches.</p>
    
    <h3>f-Strings (Python 3.6+)</h3>
    
    <p><dfn>f-strings</dfn> (formatted string literals) provide a concise and readable way to include expressions inside string literals.</p>
    
    <pre><code>name = "Alice"
age = 30
message = f"Hello, {name}! You are {age} years old."
print(message)  # Output: Hello, Alice! You are 30 years old.</code></pre>
    
    <p>You can include expressions inside the curly braces:</p>
    
    <pre><code>price = 49.95
quantity = 3
total = f"Total: ${price * quantity:.2f}"
print(total)  # Output: Total: $149.85</code></pre>
    
    <h3>The <code>format()</code> Method</h3>
    
    <p>Before f-strings, the <code>str.format()</code> method was the preferred way to format strings:</p>
    
    <pre><code>name = "Bob"
age = 25
message = "Hello, {}! You are {} years old.".format(name, age)
print(message)  # Output: Hello, Bob! You are 25 years old.</code></pre>
    
    <p>You can use numbered placeholders to rearrange arguments:</p>
    
    <pre><code>message = "The {1} contains {0}.".format("fruit", "basket")
print(message)  # Output: The basket contains fruit.</code></pre>
    
    <div class="note">
        <p><strong>Note:</strong> While the <code>%</code> operator (e.g., <code>"Hello, %s" % name</code>) still works, it's considered outdated and not recommended for new code.</p>
    </div>
    
    <h3>Common Formatting Specifiers</h3>
    
    <p>Both f-strings and <code>format()</code> use similar formatting specifiers:</p>
    
    <ul>
        <li><code>{variable:.2f}</code> - Float with 2 decimal places</li>
        <li><code>{variable:10s}</code> - String with a minimum width of 10 characters</li>
        <li><code>{variable:<10}</code> - Left-aligned with a width of 10</li>
        <li><code>{variable:>10}</code> - Right-aligned with a width of 10</li>
        <li><code>{variable:^10}</code> - Center-aligned with a width of 10</li>
        <li><code>{variable:,}</code> - Number with thousand separators</li>
    </ul>
    
    <p>To format a variable <var>x</var> with both alignment and precision, use: <code>{x:&gt;10.2f}</code></p>
    
    <p>For more information, type <kbd>help('FORMATTING')</kbd> in a Python interactive shell.</p>
</section>

Accessibility Considerations

When formatting text and using headings, keep accessibility in mind to ensure your content is usable by everyone, including people with disabilities.

Headings and Screen Readers

  • Maintain heading hierarchy: Screen reader users often navigate pages by headings. A logical hierarchy helps them understand the page structure.
  • Don't skip heading levels: Going from <h1> directly to <h3> can confuse users about the document structure.
  • Use headings for structure, not styling: If you need larger or smaller text, use CSS instead of misusing heading elements.

Text Formatting and Readability

  • Use semantic elements: Screen readers announce elements like <strong> and <em> differently, conveying their meaning.
  • Don't rely solely on color: Use formatting elements like <strong> or <mark> in addition to color for emphasis.
  • Provide context for abbreviations: Use <abbr> with a title attribute to explain abbreviations and acronyms.
  • Use proper list structures: Screen readers announce lists and count the number of items, helping users understand the content.

Accessible Text Formatting Example:

<!-- Not accessible -->
<p>The deadline is April 15, 2025 (marked in red text via CSS).</p>

<!-- More accessible -->
<p>The deadline is <strong>April 15, 2025</strong>.</p>

<!-- Not accessible -->
<p>Please submit your TPS reports.</p>

<!-- More accessible -->
<p>Please submit your <abbr title="Test Procedure Specification">TPS</abbr> reports.</p>

SEO Considerations

Proper use of headings and text formatting also affects how search engines understand and rank your content.

Headings and SEO

  • Use <h1> for your main title: Search engines give more weight to <h1> content, treating it as the primary topic of your page.
  • Include keywords in headings: Search engines use heading content to understand what your page is about.
  • Keep headings descriptive but concise: Aim for clear, meaningful headings that accurately describe the content that follows.
  • Use a logical hierarchy: Search engines use the heading structure to understand the organization of your content.

Text Formatting and SEO

  • Use semantic elements meaningfully: Search engines may give slightly more weight to emphasized content.
  • Don't overuse emphasis: Too many emphasized elements dilute their impact and can appear spammy.
  • Break up text with paragraphs and lists: Well-structured content is more readable for both humans and search engines.
  • Use descriptive text for links: Rather than "click here," use descriptive text that includes relevant keywords.

Best Practices Summary

Let's review the key best practices for using headings and text formatting in HTML:

For Headings:

  • Use only one <h1> per page
  • Follow a logical hierarchy without skipping levels
  • Keep headings concise and descriptive
  • Use headings for structure, not for styling text
  • Include keywords in headings for better SEO

For Text Formatting:

  • Choose semantic elements over presentational ones when possible
  • Use <strong> for importance, <em> for emphasis
  • Use <b> and <i> only when no semantic element fits the purpose
  • Apply formatting elements sparingly for maximum effect
  • Use appropriate elements for code, quotes, and technical content
  • Use <abbr> with title attribute for abbreviations
  • Remember entities for special characters (&lt;, &gt;, &amp;, etc.)

General Text Best Practices:

  • Break content into readable paragraphs (generally 3-5 sentences)
  • Use lists for groups of related items or steps
  • Consider both accessibility and SEO when structuring content
  • Maintain a consistent style throughout your document
  • Use CSS for visual styling rather than HTML for presentation

Practical Exercise

Let's apply what you've learned with a practical exercise that practices text formatting and headings.

Exercise: Format a Recipe Page

Convert the following plain text recipe into properly formatted HTML using appropriate headings and text formatting elements:

CLASSIC CHOCOLATE CHIP COOKIES

These homemade chocolate chip cookies are soft, chewy, and loaded with chocolate chips. Perfect for dessert, snacks, or special occasions!

INGREDIENTS

- 2 1/4 cups all-purpose flour
- 1 teaspoon baking soda
- 1 teaspoon salt
- 1 cup (2 sticks) unsalted butter, softened
- 3/4 cup granulated sugar
- 3/4 cup packed brown sugar
- 2 large eggs
- 2 teaspoons vanilla extract
- 2 cups semi-sweet chocolate chips

INSTRUCTIONS

1. Preheat oven to 375°F (190°C).

2. In a small bowl, combine flour, baking soda, and salt.

3. In a large bowl, cream together butter, granulated sugar, and brown sugar until light and fluffy. Beat in eggs one at a time, then stir in vanilla.

4. Gradually blend in the dry ingredients. Stir in chocolate chips by hand.

5. Drop rounded tablespoons of dough onto ungreased baking sheets.

6. Bake for 9-11 minutes or until golden brown. Allow cookies to cool on baking sheet for 2 minutes before removing to wire racks to cool completely.

NUTRITION INFORMATION (PER COOKIE)

Calories: 150
Fat: 7g
Carbohydrates: 20g
Protein: 2g

NOTES

- For softer cookies, bake for the minimum time suggested.
- Store in an airtight container for up to 5 days.
- Dough can be frozen for up to 3 months.

WARNING: Contains wheat, dairy, and eggs.

Recipe adapted from Grandma's Cookbook, 1965.
                

Your task is to convert this plain text into a properly formatted HTML document with:

  • Appropriate heading levels
  • Proper lists (ordered for instructions, unordered for ingredients)
  • Semantic text formatting (emphasis, strong importance, etc.)
  • Special characters and entities where needed
  • Any other appropriate HTML elements

Example Solution:

<article class="recipe">
    <h1>Classic Chocolate Chip Cookies</h1>
    
    <p>These homemade chocolate chip cookies are soft, chewy, and loaded with chocolate chips. Perfect for dessert, snacks, or special occasions!</p>
    
    <h2>Ingredients</h2>
    <ul>
        <li>2&frac14; cups all-purpose flour</li>
        <li>1 teaspoon baking soda</li>
        <li>1 teaspoon salt</li>
        <li>1 cup (2 sticks) unsalted butter, softened</li>
        <li>&frac34; cup granulated sugar</li>
        <li>&frac34; cup packed brown sugar</li>
        <li>2 large eggs</li>
        <li>2 teaspoons vanilla extract</li>
        <li>2 cups semi-sweet chocolate chips</li>
    </ul>
    
    <h2>Instructions</h2>
    <ol>
        <li>Preheat oven to 375&deg;F (190&deg;C).</li>
        
        <li>In a small bowl, combine flour, baking soda, and salt.</li>
        
        <li>In a large bowl, cream together butter, granulated sugar, and brown sugar until light and fluffy. Beat in eggs one at a time, then stir in vanilla.</li>
        
        <li>Gradually blend in the dry ingredients. Stir in chocolate chips by hand.</li>
        
        <li>Drop rounded tablespoons of dough onto ungreased baking sheets.</li>
        
        <li>Bake for <strong>9-11 minutes</strong> or until golden brown. Allow cookies to cool on baking sheet for 2 minutes before removing to wire racks to cool completely.</li>
    </ol>
    
    <h2>Nutrition Information <small>(per cookie)</small></h2>
    <ul>
        <li><b>Calories:</b> 150</li>
        <li><b>Fat:</b> 7g</li>
        <li><b>Carbohydrates:</b> 20g</li>
        <li><b>Protein:</b> 2g</li>
    </ul>
    
    <h2>Notes</h2>
    <ul>
        <li>For <em>softer</em> cookies, bake for the minimum time suggested.</li>
        <li>Store in an airtight container for up to 5 days.</li>
        <li>Dough can be frozen for up to 3 months.</li>
    </ul>
    
    <p><mark><strong>WARNING:</strong> Contains wheat, dairy, and eggs.</mark></p>
    
    <p><small>Recipe adapted from <cite>Grandma's Cookbook</cite>, 1965.</small></p>
</article>

Conclusion

In this tutorial, we've explored the essential HTML elements for formatting text and creating headings. These elements are fundamental building blocks for creating well-structured, accessible, and SEO-friendly web content.

Remember that HTML is primarily about meaning and structure, not presentation. Choose elements based on their semantic purpose, and use CSS (which we'll cover in future lessons) for styling the visual appearance.

By mastering these text formatting and heading elements, you've taken an important step in your journey to becoming a proficient web developer. In the next lessons, we'll build on this foundation by exploring more complex HTML elements and introducing CSS for styling your content.

Additional Resources