代表者の戯言

HTML + CSS Table Techniques

Use the following tips when creating tables with HTML and CSS.

The roles of col and row

In this context, col refers to a "column" and row refers to a "row"—opposite to how they're used in Excel. The caption element defines the table's title. It can be styled later using CSS (e.g., caption-side: top;), making it beneficial to include.


Example HTML


<table>

<caption>Crepe Batter Ingredients</caption>

<thead>

<tr>

<th scope="col">Ingredient</th>

<th scope="col">Amount</th>

<th scope="col">Preparation</th>

</tr>

</thead>

<tbody>

<tr>

<th scope="row">Flour</th>

<td>100g</td>

<td>Sift before use</td>

</tr>

<tr>

<th scope="row">Egg</th>

<td>1</td>

<td>Bring to room temperature and beat</td>

</tr>

<tr>

<th scope="row">Milk</th>

<td>200cc</td>

<td>Take out of refrigerator early</td>

</tr>

</tbody>

</table>

Crepe Batter Ingredients
Ingredient Amount Preparation
Flour 100g Sift before use
Egg 1 Bring to room temperature and beat
Milk 200cc Take out of refrigerator early

CSS Example


table {

width: 650px;

border: 1px solid #666666;

border-collapse: collapse;

background-color: #fff;

}


th {

border: 1px solid #666666;

text-align: left;

padding: 10px;

background-color: #dddddd;

}


td {

border: 1px solid #666666;

padding: 10px;

vertical-align: top;

}


Rendered Table Preview

According to ChatGPT, "there are several reasons to deliberately include HTML elements such as col, row, and caption even though the display may not change whether they are written or not."


Semantics (Meaning)

HTML is a language not only for visual presentation but also for conveying meaning. For example:


Using caption clarifies what the table is about.


Using col or colgroup conveys structural meaning, such as “these columns are grouped.”

→ This makes the HTML meaningful to both humans and machines.


Accessibility (especially for screen reader support)

For users who rely on the web without using their vision, semantic elements are extremely important.


With a caption, screen readers can explain, “This is a table about ○○.”


Using attributes like scope="col" ensures that headers for rows and columns are read correctly.

→ This helps create a web experience that is friendly to everyone.


Integration with Styles and Scripts


By applying styles to the col element, you can uniformly style entire columns.


Elements like row, colgroup, and caption are also useful when manipulating structured data with JavaScript.

→ This results in code that is easier to manage and more extensible.


Maintainability and Readability


Developers can quickly understand what kind of data the table contains and how it is structured.

→ This makes team development and future updates easier.