HTML Block and Inline Elements

In HTML, most elements can be classified as either Block-level elements or Inline elements. Understanding the difference between these two is crucial for mastering HTML layout.

Block-level Elements

Block-level elements appear as "blocks" on the page, with the following characteristics:

  • Take up a full line: Block-level elements always start on a new line, and subsequent elements are also pushed to the next line.
  • Occupy full width: They will expand to fill the entire width of their parent container.
  • Can set width and height: You can set width, height, margin, and padding for block-level elements.

Common block-level elements include:

  • <div>
  • <h1> - <h6>
  • <p>
  • <form>
  • <ul>, <ol>, <li>
  • <table>

Inline Elements

Inline elements appear "within the line," meaning they:

  • Don't start a new line: Inline elements don't break the text flow; they line up with other inline elements and text content on the same line.
  • Width is determined by content: Their width is just the width of their content, not spanning the entire container.
  • Setting width and height is usually ineffective: Directly setting width, height, and vertical margin and padding for inline elements usually doesn't work (horizontal margin and padding do work).

Common inline elements include:

  • <span>
  • <a>
  • <img>
  • <strong>, <em>
  • <b>, <i>
  • <input>, <button>

The <div> Element - Generic Block Container

The <div> (Division) element is a generic block-level container. It has no semantic meaning by itself; its main purpose is to serve as a container for other HTML elements, allowing you to style them with CSS or manipulate them with JavaScript.

<div> is one of the most commonly used elements for building web page layouts.

Example: Creating a simple page layout using <div>

<div style="background-color:#f1f1f1; padding:20px;">
  <h2>London</h2>
  <p>London is the capital and largest city of England.</p>
</div>

<div style="background-color:#ddd; padding:20px;">
  <h2>Paris</h2>
  <p>Paris is the capital of France.</p>
</div>

The <span> Element - Generic Inline Container

The <span> element is a generic inline container. Like <div>, it has no specific semantic meaning. Its main use is to wrap a small piece of text or inline elements to apply special styles or manipulate them with JavaScript, without affecting the overall layout.

Example: Using <span> to style part of a sentence

<p>My mother has <span style="color:blue; font-weight:bold;">blue</span> eyes.</p>

In this example, only the word "blue" becomes blue and bold, while the entire paragraph's layout remains unchanged.