阿里云主机折上折
  • 微信号
Current Site:Index > <th> - table header cell

<th> - table header cell

Author:Chuan Chen 阅读数:44618人阅读 分类: HTML

Basic Concept of the <th> Tag

The <th> tag is used to define header cells in HTML tables, standing for "table header." Unlike regular <td> cells, <th> elements have bold and centered text by default and semantically indicate that the cell is a column or row heading.

<table>
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Occupation</th>
  </tr>
  <tr>
    <td>Zhang San</td>
    <td>28</td>
    <td>Engineer</td>
  </tr>
</table>

Attributes of the <th> Tag

The <th> tag supports various attributes to enhance functionality:

  1. colspan - Spans multiple columns
<th colspan="2">Personal Information</th>
  1. rowspan - Spans multiple rows
<th rowspan="3">Quarter</th>
  1. scope - Defines the associated scope
<th scope="col">Price</th>
<th scope="row">Product A</th>
  1. headers - Associates with other headers
<th id="name">Name</th>
<td headers="name">Li Si</td>

Differences Between <th> and <td>

Feature <th> <td>
Default Style Bold and centered Regular left-aligned
Semantic Meaning Header Data cell
Screen Reader Recognized as a header Recognized as data
<table>
  <tr>
    <th>Item</th>
    <th>Quantity</th>
  </tr>
  <tr>
    <td>Apple</td>
    <td>5</td>
  </tr>
</table>

Custom Styling Example

Although <th> has default styles, they can be fully customized with CSS:

th {
  background-color: #4CAF50;
  color: white;
  padding: 15px;
  text-align: left;
  border-bottom: 2px solid #ddd;
}

th:hover {
  background-color: #45a049;
}

<th> in Responsive Tables

On small-screen devices, tables can be converted to a card layout using CSS:

@media screen and (max-width: 600px) {
  table, thead, tbody, th, td, tr {
    display: block;
  }
  
  th {
    position: absolute;
    top: -9999px;
    left: -9999px;
  }
  
  td:before {
    content: attr(data-th);
    font-weight: bold;
    display: inline-block;
    width: 120px;
  }
}

Accessibility Practices

To enhance accessibility, it is recommended to:

  1. Always use the scope attribute
  2. Add <caption> for complex tables
  3. Use aria-describedby to associate descriptions
<table aria-describedby="table-desc">
  <caption>2023 Sales Data</caption>
  <tr>
    <th scope="col" id="product">Product</th>
    <th scope="col" id="sales">Sales</th>
  </tr>
  <tr>
    <td headers="product">A</td>
    <td headers="sales">1200</td>
  </tr>
</table>
<p id="table-desc">Unit: pieces</p>

Dynamically Generating Headers

Example of dynamically creating headers with JavaScript:

const data = [
  { id: 1, name: 'Product A', price: 100 },
  { id: 2, name: 'Product B', price: 200 }
];

function createTable(data) {
  const table = document.createElement('table');
  const thead = document.createElement('thead');
  const headerRow = document.createElement('tr');
  
  // Use the first object's properties as headers
  Object.keys(data[0]).forEach(key => {
    const th = document.createElement('th');
    th.textContent = key;
    headerRow.appendChild(th);
  });
  
  thead.appendChild(headerRow);
  table.appendChild(thead);
  
  // Add data rows...
  document.body.appendChild(table);
}

Header Grouping

For complex tables, use <thead>, <tfoot>, and <tbody> for grouping:

<table>
  <thead>
    <tr>
      <th colspan="3">2023 Annual Report</th>
    </tr>
    <tr>
      <th>Quarter</th>
      <th>Revenue</th>
      <th>Expenses</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Q1</td>
      <td>10000</td>
      <td>8000</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th>Total</th>
      <td>40000</td>
      <td>32000</td>
    </tr>
  </tfoot>
</table>

Header Sorting Functionality

Complete example of implementing click-to-sort headers:

<table id="sortable-table">
  <thead>
    <tr>
      <th onclick="sortTable(0)">Name ↑↓</th>
      <th onclick="sortTable(1)">Age ↑↓</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>Zhang San</td><td>25</td></tr>
    <tr><td>Li Si</td><td>30</td></tr>
  </tbody>
</table>

<script>
function sortTable(columnIndex) {
  const table = document.getElementById('sortable-table');
  const rows = Array.from(table.querySelectorAll('tbody tr'));
  const isAsc = table.querySelector(`th:nth-child(${columnIndex+1})`).classList.toggle('asc');
  
  rows.sort((a, b) => {
    const aVal = a.cells[columnIndex].textContent;
    const bVal = b.cells[columnIndex].textContent;
    return isAsc ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
  });
  
  table.tBodies[0].append(...rows);
}
</script>

<style>
th.asc::after { content: ' ↑'; }
th:not(.asc)::after { content: ' ↓'; }
th { cursor: pointer; }
</style>

Fixed Header Implementation

CSS method for implementing fixed headers:

.table-container {
  height: 300px;
  overflow: auto;
}

table {
  width: 100%;
}

thead th {
  position: sticky;
  top: 0;
  background: white;
  box-shadow: 0 2px 2px -1px rgba(0,0,0,0.4);
}
<div class="table-container">
  <table>
    <thead>
      <tr><th>Fixed Header 1</th><th>Fixed Header 2</th></tr>
    </thead>
    <tbody>
      <!-- Lots of data rows -->
    </tbody>
  </table>
</div>

Headers with Form Controls

Example of form controls within headers:

<table>
  <thead>
    <tr>
      <th>
        <input type="checkbox" id="select-all">
        <label for="select-all">Select All</label>
      </th>
      <th>
        <select onchange="filterTable(this.value)">
          <option value="">All Departments</option>
          <option value="IT">IT Department</option>
        </select>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="checkbox"></td>
      <td>IT Department</td>
    </tr>
  </tbody>
</table>

<script>
function filterTable(dept) {
  document.querySelectorAll('tbody tr').forEach(row => {
    row.style.display = !dept || row.cells[1].textContent === dept ? '' : 'none';
  });
}
</script>

Multi-line Text in Headers

Styling solution for multi-line text in headers:

th.multiline {
  white-space: normal;
  word-wrap: break-word;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}
<table>
  <tr>
    <th class="multiline">This is a very<br>long header title<br>that needs line breaks</th>
    <th>Regular Header</th>
  </tr>
</table>

Header Icons Integration

Ways to add icons to headers:

  1. Using font icons
<th><i class="fas fa-user"></i> User</th>
  1. Using SVG
<th>
  <svg width="16" height="16" viewBox="0 0 24 24">
    <path d="M12 2L1 12h3v9h16v-9h3L12 2z"/>
  </svg>
  Home
</th>
  1. Using background images
th.sortable {
  background-image: url('sort-icon.png');
  background-position: right center;
  background-repeat: no-repeat;
  padding-right: 20px;
}

Header and Data Association

Using data-* attributes to enhance header-data association:

<table>
  <thead>
    <tr>
      <th data-field="name" data-type="string">Name</th>
      <th data-field="score" data-type="number">Score</th>
    </tr>
  </thead>
  <tbody>
    <tr data-name="Zhang San" data-score="85"></tr>
  </tbody>
</table>

<script>
document.querySelectorAll('th[data-field]').forEach(th => {
  const field = th.dataset.field;
  const type = th.dataset.type;
  
  th.addEventListener('click', () => {
    // Determine sorting logic based on data-type
  });
});
</script>

Header Tooltips

Adding detailed tooltips to headers:

<th title="This is detailed explanation text">Brief Title</th>

<!-- Or more complex tooltips -->
<th>
  Sales
  <span class="tooltip">Includes total sales from all channels</span>
</th>

<style>
.tooltip {
  visibility: hidden;
  width: 200px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px;
  position: absolute;
  z-index: 1;
  bottom: 125%;
  left: 50%;
  margin-left: -100px;
  opacity: 0;
  transition: opacity 0.3s;
}

th:hover .tooltip {
  visibility: visible;
  opacity: 1;
}
</style>

Headers and Print Styles

Optimizing header display for printing with CSS:

@media print {
  thead {
    display: table-header-group;
  }
  
  th {
    background-color: #fff !important;
    color: #000 !important;
    border-bottom: 2px solid #000;
  }
  
  table {
    page-break-inside: avoid;
  }
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:-表格行

下一篇:<td>-表格数据单元格

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.