HTML

Introduction to Web and HTML

How the Web Works What is HTML Why Learn HTML

Spanning Rows and Columns

Spanning Rows and Columns

HTML tables provide the flexibility to merge or span rows and columns, creating unique layouts and designs. In this section, we'll explore how to span rows and columns within a table.

Spanning Rows

Spanning rows is a way to make a cell cover multiple rows. This is often used for table headers that describe a category for a range of data. To span rows, you can use the rowspan attribute on a cell.

Here's an example of spanning rows:

<table>
  <tr>
    <th rowspan="2">Category</th>
    <th>Product</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>Item 1</td>
    <td>$10.00</td>
  </tr>
  <tr>
    <td>Item 2</td>
    <td>$15.00</td>
  </tr>
</table>

In this example, the "Category" cell spans two rows, covering the "Item 1" and "Item 2" cells in the second column.

Spanning Columns

Spanning columns allows a cell to cover multiple columns. This is often used to merge cells in the data section of the table. To span columns, you can use the colspan attribute on a cell.

Here's an example of spanning columns:

<table>
  <tr>
    <th>Product</th>
    <th>Price</th>
  </tr>
  <tr>
    <td colspan="2">Special Discount</td>
  </tr>
  <tr>
    <td>Item 1</td>
    <td>$10.00</td>
  </tr>
  <tr>
    <td>Item 2</td>
    <td>$15.00</td>
  </tr>
</table>

In this example, the "Special Discount" cell spans two columns in the first row.

Combining Row and Column Spanning

You can also combine both row and column spanning to create complex layouts. For instance, you could have a cell that spans both rows and columns, effectively creating a larger cell in the table.

<table>
  <tr>
    <th>Product</th>
    <th>Price</th>
  </tr>
  <tr>
    <td rowspan="2" colspan="2">Special Discount</td>
  </tr>
  <tr>
    <!-- Empty row to maintain the structure -->
  </tr>
  <tr>
    <td>Item 1</td>
    <td>$10.00</td>
  </tr>
  <tr>
    <td>Item 2</td>
    <td>$15.00</td>
  </tr>
</table>

In this example, the "Special Discount" cell spans both rows and columns.

Styling Spanned Cells

Spanned cells can be styled just like regular cells. You can use CSS to apply borders, background colors, and other visual effects.

In summary, spanning rows and columns in HTML tables allows you to create unique and complex layouts. Whether you're designing tables for data presentation or visual effects, understanding how to use rowspan and colspan attributes is a valuable skill in web development.