HTML Part 4
HTML Part 4
A table organizes data into rows and columns. It allows you to quickly find
information by relating data points. For example, a table might show people's names
and their ages, like Chris (38), Dennis (45), Sarah (29), and Karen (47).
Tables are a common way to present structured data, even outside the web. HTML
provides a way to display tables online to make data easy to understand.
Tables help users compare data by aligning rows and columns. For instance, if you're
looking for a planet with 62 moons, you can easily find the row with that information
by matching the relevant column.
HTML tables are also accessible for visually impaired users. Screen readers can
interpret tables, making them usable for everyone.
Table Styling
To make tables more readable, you should style them using CSS. This guide focuses
on the HTML part, but after building a table, you'll likely want to improve its
appearance with CSS.
Tables should only be used for data, not for laying out web pages. In the past, people
used tables to structure page content, but that practice is outdated. CSS is a better tool
for layout because:
1. Add the <table> tag inside the <body> section of your HTML.
2. Inside the <table>, use the <td> tag to create cells. Each <td> represents a single cell.
Example:
html
Copy code
<td>Hi, I'm your first cell.</td>
To make multiple cells in a row, add more <td> tags like this:
html
Copy code
<td>Hi, I'm your first cell.</td><td>I'm your second cell.</td><td>I'm your third
cell.</td><td>I'm your fourth cell.</td>
This creates one row with four cells. To add more rows, wrap each group of cells in a
<tr> tag, like this:
html
Copy code
<tr>
<td>Hi, I'm your first cell.</td>
<td>I'm your second cell.</td>
<td>I'm your third cell.</td>
<td>I'm your fourth cell.</td></tr>
To make table headers (like column or row titles), use the <th> tag. For example:
html
Copy code
<table>
<tr>
<th>Person</th>
<th>Age</th>
</tr>
<tr>
<td>Chris</td>
<td>38</td>
</tr>
<tr>
<td>Dennis</td>
<td>45</td>
</tr></table>
Headers are bold and centered by default, making the data easier to understand.
Merging Cells
Sometimes, you want a cell to span multiple columns or rows. For this, you can use
the colspan and rowspan attributes.
html
Copy code
<td colspan="2">This cell spans two columns.</td>
Example of a cell spanning two rows:
html
Copy code
<td rowspan="2">This cell spans two rows.</td>
To style an entire column, you can use the <col> and <colgroup> elements. This lets you
apply styles like background color or width to all cells in a column without needing to
style each cell individually.
Example:
html
Copy code
<table>
<colgroup>
<col style="background-color: yellow">
</colgroup>
<tr>
<th>Data 1</th>
<th>Data 2</th>
</tr>
<tr>
<td>Value 1</td>
<td>Value 2</td>
</tr></table>
This sets the background color for the entire first column.