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!
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.
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.
<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>To help identify the columns in a table, you can use header cells. These are specified using the <th> tag instead of <td>.
<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>You can span rows and columns using the rowspan and colspan attributes.
<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>HTML tables can be styled using CSS. You can adjust the width, border, padding, and more.
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}Which tag defines a table?
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.
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);
}
}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! 🎉