Problem Statement
What is the purpose of the scope attribute in <th> tags?
Explanation
The scope attribute specifies whether a header cell is for a column or row, improving table accessibility. The scope attribute can have four values. Scope equals col indicates the header is for a column. Scope equals row indicates the header is for a row. Scope equals colgroup indicates the header is for a group of columns. Scope equals rowgroup indicates the header is for a group of rows. Using the scope attribute helps screen readers associate header cells with data cells correctly. This is crucial for visually impaired users to understand table relationships. For simple tables, browsers can often infer the scope automatically. However, for complex tables with multiple header levels or irregular structures, explicitly setting scope is important. The scope attribute is a key part of creating accessible tables and is considered a web accessibility best practice.
Code Solution
SolutionRead Only
<!-- Column headers with scope -->
<table>
<tr>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">Country</th>
</tr>
<tr>
<td>John</td>
<td>25</td>
<td>USA</td>
</tr>
</table>
<!-- Row headers with scope -->
<table>
<tr>
<th scope="row">Monday</th>
<td>9:00 AM</td>
<td>Meeting</td>
</tr>
<tr>
<th scope="row">Tuesday</th>
<td>2:00 PM</td>
<td>Workshop</td>
</tr>
</table>
<!-- Mixed headers -->
<table>
<tr>
<th></th>
<th scope="col">Q1</th>
<th scope="col">Q2</th>
</tr>
<tr>
<th scope="row">Sales</th>
<td>$10k</td>
<td>$12k</td>
</tr>
<tr>
<th scope="row">Profit</th>
<td>$2k</td>
<td>$3k</td>
</tr>
</table>