HTML Tables Tutorial

What are the HTML Tables?

  1. HTML tables are used to structure tabular data on web pages.
  2. They are made up of rows and columns, with each cell containing a piece of data.
  3. Tables can be used to display any type of tabular data, such as product catalogs, price lists, or contact information.

Table Structure

  1. <table>: This element defines the entire table.
  2. <tr> (Table Row): Each row in the table is defined using this element.
  3. <td> (Table Data): This element represents individual cells within the table. Each <td> element should be placed inside a <tr>.
  4. <th> (Table Header): Similar to <td>, but used for header cells. Header cells are typically bold and centered.
<table>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
    </tr>
    <tr>
      <td>Data 1, Row 1</td>
      <td>Data 2, Row 1</td>
    </tr>
    <tr>
      <td>Data 1, Row 2</td>
      <td>Data 2, Row 2</td>
    </tr>
  </table>
  
HTML5 Tables

Table Attributes

  1. You can use various attributes to modify the appearance and behavior of tables.
  2. border: Specifies the border width around the table. (Deprecated; use CSS for styling instead.)
  3. cellpadding: Defines the space between the cell content and cell border.
  4. cellspacing: Specifies the space between cells.
  5. width and height: Sets the width and height of the table.

Styling Tables with CSS

  1. To style tables, use CSS. You can apply CSS rules to the table, rows, cells, or headers as needed.
<style>
    table { 
      border-collapse: collapse;
    }
    th, td {
      border: 1px solid #000;
      padding: 8px;
      text-align: center;
    }
    th {
      background-color: #333;
      color: #fff;
    }
</style>
  
Styling Tables in HTML5

Spanning Rows and Columns

  1. You can use the colspan and rowspan attributes to make cells span multiple rows or columns.
<table>
    <tr>
        <th>Header 1</th>
        <th>Header 2</th>
    </tr>
    <tr>
        <td>Data 1, Row 1</td>
        <td>Data 2, Row 1</td>
    </tr>
    <tr>
        <td colspan="2">Spanned Cell</td>
    </tr>
</table>
    

Adding Captions

  1. You can add a caption to your table using the <caption> element, which is placed immediately after the opening <table> tag.

Accessing Tables with JavaScript

  1. To manipulate tables using JavaScript, you can use the Document Object Model (DOM).
// Access the table element
var table = document.getElementById('myTable');

// Access a specific cell
var cell = table.rows[1].cells[0];