Tables in HTML

HTML Tables: A Complete Guide

HTML tables allow us to organize and display data in a structured format using rows and columns. In this guide, we will learn how to create and style tables, merge cells, and ensure responsiveness for different devices.

1️⃣ Creating a Basic HTML Table

A simple HTML table consists of the <table> element, with rows defined using <tr> and cells using <td>.

<table border="1">
  <tr>
    <td>Row 1, Column 1</td>
    <td>Row 1, Column 2</td>
  </tr>
  <tr>
    <td>Row 2, Column 1</td>
    <td>Row 2, Column 2</td>
  </tr>
</table>

2️⃣ Table Rows & Cells (`<tr>` & `<td>`)

  • <tr> defines a table row.
  • <td> defines a table cell within a row.

Example: Multiple Rows in a Table

<table border="1">
  <tr>
    <td>Alice</td>
    <td>25</td>
  </tr>
  <tr>
    <td>Bob</td>
    <td>30</td>
  </tr>
</table>

3️⃣ Table Headers (`<th>`)

The <th> element defines header cells in a table. Headers are typically bold and centered by default.

Example: Using <th> for Column Headers

<table border="1">
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Alice</td>
    <td>25</td>
  </tr>
</table>

4️⃣ Merging Cells with `colspan` & `rowspan`

  • colspan: Merges columns horizontally.
  • rowspan: Merges rows vertically.

Example: Using `colspan` to Merge Columns

<table border="1">
  <tr>
    <th colspan="2">Full Name</th>
  </tr>
  <tr>
    <td>Alice</td>
    <td>Bob</td>
  </tr>
</table>

5️⃣ Grouping Table Sections (`<thead>`, `<tbody>`, `<tfoot>`)

Using these elements helps organize and structure a table for better readability and accessibility.

Example: Grouping Table Content

<table border="1">
  <thead>
    <tr>
      <th>Product</th>
      <th>Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Laptop</td>
      <td>$800</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Total</td>
      <td>$800</td>
    </tr>
  </tfoot>
</table>

6️⃣ Styling Tables with CSS

We can use CSS to improve table appearance by adding borders, background colors, and spacing.

Example: Styling a Table

<style>
  table {
    width: 100%;
    border-collapse: collapse;
  }
  th, td {
    padding: 8px;
    text-align: center;
    border: 1px solid #ddd;
  }
  th {
    background-color: #f2f2f2;
  }
  tr:nth-child(even) {
    background-color: #f9f9f9;
  }
</style>

7️⃣ Making Tables Responsive

Tables can be made scrollable to fit smaller screens.

Example: Responsive Table

<div style="overflow-x:auto;">
  <table>
    <!-- Table content here -->
  </table>
</div>

8️⃣ Best Practices for Using Tables

  • Use tables only for structured data, not for layout.
  • Apply CSS styles to enhance readability.
  • Ensure tables are responsive for different screen sizes.

Enhancing HTML Tables with Advanced Features

Beyond the basic structure of HTML tables, we can incorporate interactive and advanced functionalities to improve usability, accessibility, and responsiveness. Below are several key enhancements for better table management.

9️⃣ Accessibility Best Practices for Tables

To make tables accessible for screen readers, we should use attributes like scope and headers to define relationships between table headers and data cells.

Example: Using `scope` and `headers` Attributes

<table border="1">
  <tr>
    <th id="product">Product</th>
    <th id="price">Price</th>
  </tr>
  <tr>
    <td headers="product">Laptop</td>
    <td headers="price">$800</td>
  </tr>
</table>

🔟 Exporting Table Data (CSV, Excel, PDF)

Allowing users to download table data enhances usability. Below is a JavaScript function to export an HTML table to a CSV file.

Example: Exporting Table to CSV

<button onclick="exportTableToCSV('table-data.csv')">Download CSV</button>

<script>
function exportTableToCSV(filename) {
    let csv = [];
    let rows = document.querySelectorAll("table tr");

    for (let row of rows) {
        let cols = row.querySelectorAll("td, th");
        let rowData = [];
        for (let col of cols) {
            rowData.push(col.innerText);
        }
        csv.push(rowData.join(","));
    }

    let csvFile = new Blob([csv.join("\n")], { type: "text/csv" });
    let link = document.createElement("a");
    link.href = URL.createObjectURL(csvFile);
    link.download = filename;
    link.click();
}
</script>

1️⃣1️⃣ Sorting Table Columns with JavaScript

Adding clickable headers to sort table columns makes it easier to organize data dynamically.

Example: Sortable Table

<script>
function sortTable(n) {
    let table = document.querySelector("table");
    let rows = Array.from(table.rows).slice(1);
    let isAscending = table.dataset.order !== "asc";

    rows.sort((rowA, rowB) => {
        let cellA = rowA.cells[n].innerText.trim();
        let cellB = rowB.cells[n].innerText.trim();
        return isAscending ? cellA.localeCompare(cellB) : cellB.localeCompare(cellA);
    });

    table.tBodies[0].append(...rows);
    table.dataset.order = isAscending ? "asc" : "desc";
}
</script>

<table border="1" data-order="asc">
  <tr>
    <th onclick="sortTable(0)">Name ⬆⬇</th>
    <th onclick="sortTable(1)">Age ⬆⬇</th>
  </tr>
  <tr>
    <td>Alice</td>
    <td>25</td>
  </tr>
  <tr>
    <td>Bob</td>
    <td>30</td>
  </tr>
</table>

1️⃣2️⃣ Interactive Searchable Table

Adding a search feature allows users to filter table content dynamically.

Example: Searchable Table

<input type="text" id="searchInput" onkeyup="searchTable()" placeholder="Search for names...">

<script>
function searchTable() {
    let input = document.getElementById("searchInput").value.toLowerCase();
    let rows = document.querySelectorAll("table tr");

    rows.forEach((row, index) => {
        if (index === 0) return; 
        let text = row.innerText.toLowerCase();
        row.style.display = text.includes(input) ? "" : "none";
    });
}
</script>

<table border="1">
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Alice</td>
    <td>25</td>
  </tr>
  <tr>
    <td>Bob</td>
    <td>30</td>
  </tr>
</table>

✅ Best Practices for HTML Tables

  • Use tables only for structured data, not for page layout.
  • Apply CSS for better table readability and responsiveness.
  • Use thead, tbody, and tfoot for clear structure.
  • Ensure accessibility with scope and headers attributes.

📌 Conclusion

By implementing these advanced table features, we can create dynamic, accessible, and responsive tables that enhance user experience. Sorting, searching, and exporting data improve table usability, making them more practical for real-world applications.

HTML tables are essential for displaying structured data. By utilizing headers, merging cells, and applying CSS styles, we can create well-organized and visually appealing tables. Implementing best practices ensures accessibility and usability across various devices.

Read more on Table background Image

Standard Class for table style

There are different table styles available under bootstrap design which can be added to your table design.
Read more on Bootstrap table design
HTML Meta Tags Paragraph in HTML pages Bold Tag

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    veerender

    04-10-2012

    thank u



    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer