Problem Statement
What is the difference between <td> and <th> tags?
Explanation
The td and th tags both create cells in a table, but they serve different purposes and have different semantic meanings. Understanding the difference is important for creating accessible and well-structured tables. The td tag stands for table data and is used for regular data cells. These cells contain the actual data or content of your table. By default, content in td cells is left-aligned and displayed in normal font weight. Data cells make up the body of your table where the actual information resides. You use td for all standard content cells that are not headers. The th tag stands for table header and is used for header cells that label columns or rows. By default, content in th cells is bold and center-aligned, making headers visually distinct from data. But the visual difference is just the beginning. The more important distinction is semantic. The th tag tells browsers, search engines, and assistive technologies that this cell is a header that describes other cells. This semantic meaning is crucial for accessibility. Screen readers use th tags to help visually impaired users understand table structure. When a screen reader user navigates to a data cell, it can announce the associated headers, giving context to the data. For example, if a table has column headers for Name and Age, when the user reaches a data cell containing 25, the screen reader can announce Age 25, helping the user understand what the number represents. Using th appropriately is essential for web accessibility standards like WCAG. The th tag can be used in header rows at the top of tables, header columns on the left side of tables, or both for tables with row and column headers. You can enhance th tags with the scope attribute to explicitly specify whether the header is for a column with scope equals col or a row with scope equals row. This provides even clearer relationships for assistive technologies. In complex tables with multiple header levels, proper use of th with scope becomes even more important. Best practices include using th for all cells that serve as labels or headers, using td for all cells containing data, adding scope attributes to th cells for clarity, and ensuring your table makes logical sense when read by a screen reader. A common mistake is using td for headers and just styling them to look bold. This creates tables that look correct visually but fail accessibility standards. Always use th for semantic headers. Understanding the semantic difference between td and th demonstrates knowledge of accessible web development and is a common interview topic. Many companies specifically ask about creating accessible tables in technical interviews.