HTML Tables 🎯

beginner
8 min

HTML Tables 🎯

Welcome to our comprehensive guide on HTML Tables! In this tutorial, we'll delve into the world of tabular data, and learn how to create, structure, and style HTML tables. By the end of this lesson, you'll be able to design clean, functional tables for your web projects.

Let's get started!

What are HTML Tables? 📝

HTML tables are used to organize data in a tabular format, consisting of rows and columns. They help structure and present data in a clear and easily readable manner.

Table Basics 💡

Every table begins with the <table> tag. Within this tag, you'll find rows (<tr>), and within each row, you'll find cells (<td>). Columns are defined by the order of cells within a row.

html
<table> <tr> <td>Cell 1, Row 1</td> <td>Cell 2, Row 1</td> </tr> <tr> <td>Cell 1, Row 2</td> <td>Cell 2, Row 2</td> </tr> </table>

Table Headers 💡

To help identify the columns in a table, you can use header cells. These are specified using the <th> tag instead of <td>.

html
<table> <tr> <th>Header 1, Column 1</th> <th>Header 2, Column 1</th> </tr> <tr> <td>Cell 1, Row 2</td> <td>Cell 2, Row 2</td> </tr> </table>

Spanning Rows and Columns 💡

You can span rows and columns using the rowspan and colspan attributes.

html
<table> <tr> <th colspan="2">Spanning Columns</th> </tr> <tr> <td>Cell 1, Row 1</td> <td>Cell 2, Row 1</td> </tr> <tr> <td colspan="2">Cell Spanning Two Columns</td> </tr> </table>

Table Styling 💡

HTML tables can be styled using CSS. You can adjust the width, border, padding, and more.

css
table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: left; }

Quiz 💡

Quick Quiz
Question 1 of 1

Which tag defines a table?

Accessing Table Data with JavaScript 💡

To work with table data in JavaScript, you can use the tableData property to access individual cells, and loops to iterate through rows and cells.

javascript
let table = document.querySelector('table'); let firstCell = table.rows[0].cells[0]; let firstCellData = firstCell.textContent; for (let i = 0; i < table.rows.length; i++) { for (let j = 0; j < table.rows[i].cells.length; j++) { console.log(table.rows[i].cells[j].textContent); } }

Wrapping Up 💡

In this tutorial, we've covered the basics of HTML tables, including table structure, headers, and styling. We've also touched upon accessing table data with JavaScript.

Remember, tables are a powerful tool for organizing data in web projects. Practice creating tables and experiment with various table styles. Happy coding! 🎉