<th> Tag in HTML

Learn via video course
FREE
View all courses
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
JavaScript Course With Certification: Unlocking the Power of JavaScript
JavaScript Course With Certification: Unlocking the Power of JavaScript
by Mrinal Bhattacharya
1000
4.8
Start Learning
Topics Covered

Overview

  • In HTML tables, data is organized vertically into columns. In most cases, the first row of the table would be displayed as headings or labels for each table column. The correct method to achieve this is to use <th> elements instead of <td> elements for the content in the table's first row. 
  • By default, browsers will center the contents of <th> tag in html and display them in a bold typeface. However, because of the use of this case-specific element for table headers, it is also simple to style table heads independently of the rest of the table contents.

Syntax

Attributes

AttributeValueDescription
abbrtextIt specifies a shorter version of the content in a header cell.
colspannumberIt specifies how many columns a header cell should span.
headersheader_idIt specifies one or more header cells to which a cell is associated. 
rowspannumberIt specifies how many rows a header cell should span.
alignleft, center, right, justify, charIt specifies how the cell content's horizontal alignment will be handled.
bgcolorRGBAIt specifies the background color of each cell in a column.
valignbaseline, bottom, middle, topIt specifies how a text is vertically aligned inside a cell.
scopecol, colgroup, row, rowgroupIt specifies whether a header cell is a header for a column, row, or group of columns or rows.

Global Attributes

Global attributes are properties that are shared by all HTML elements; they can be applied to all elements. They are said to be global because they are supported by both standard and non-standard HTML elements. However, they may have no effect on some.

All HTML elements, even those not specified in the standard, can have global properties. This means that any non-standard elements must nevertheless allow certain characteristics, even if using such elements renders the content non-HTML5 compliant. HTML5-compliant browsers, for example, hide content tagged as <foo hidden>...</foo>, despite the fact that <foo> is not a legitimate HTML element.

List of Global Attributes

AttributeValueDescription
accesskeyshortcut keyIt gives a tip for creating a keyboard shortcut for the currently selected element. This property is a list of characters separated by spaces. The browser should use the first one on the computer keyboard layout.
autocapitalizeoff / none, on / sentences, words, charactersControls whether and how text input is capitalized automatically when it is entered/edited by the user.
autofocusfalseIndicates that an element will be focused on page load or when the <dialogue> in which it is included is displayed.
classclassnameIt is a list of the element's classes, separated by spaces. Classes enable CSS and JavaScript to identify and access certain components using class selectors or functions.
contenteditabletrue / falseAn enumerated attribute that indicates whether or not the element should be adjustable by the user. If this is the case, the browser adjusts its widget to allow modification.
contextmenumenu-idA context menu for an element is specified. A context menu opens when the user clicks the right mouse button on an element.
datadataForms a class of attributes known as custom data attributes, which allow private information to be exchanged between HTML and its DOM representation, which scripts can exploit. All such custom data is accessible through the HTML Element interface of the element on which the attribute is set.
dirltr / rtl / autoSpecifies the base direction of directionality of the element's text.
draggabletrue / false / autoAn enumerated attribute indicates whether the element may be dragged with the Drag and Drop API.
dropzonecopy / move / linkWhen dragged data is dumped, this property specifies whether it is copied, relocated or linked.
enterkeyhintThis value indicates the action label (or icon) on virtual keyboards to display the enter key.
exportpartsIt is used to export shadow components from a nested shadow tree into a contained light tree transitively.
hiddenhiddenA Boolean attribute specifies whether or not the element is still relevant. For example, It can be used to conceal elements of the website that cannot be accessed until the login process is completed. The browser will not render such items.
IdnameDefines a unique identifier (ID) that must be unique throughout the document. It serves to identify the element when linking (through a fragment identifier), scripting, or styling (with CSS).
langlanguage-codeSpecifies the primary language for the text content of the element.
Spellchecktrue / falseSpecifies whether or not the element should be checked for spelling mistakes.
tabindexnumberSpecifies an element's tabbing order.
titletextIt contains text that represents advisory information about the element to which it belongs. Such information is typically, but not always, displayed to the user in the form of a tooltip.
slotAn element having a slot attribute is assigned to the slot established by the <slot> element whose name attribute matches the value of that slot attribute.
StylestyleStyle is used to add inline CSS to the currently selected element. It is recommended that styles be defined in a separate file or files. This attribute and the <style> element are primarily intended for rapid stylings, such as for testing reasons.
translateyes / noIt specifies whether or not the element's content should be translated when the page is localized.
xmllanguage-codeIn XHTML documents, it specifies the primary language for the element's text content.

Event Attributes

When a browser reacts to user behavior, it is referred to as an event. For example, if you click the submit button, the browser will display an information box. There are numerous event attributes available in HTML5 that can be activated using a computer language such as JavaScript.

The event attributes are mainly observers that can be added to any HTML tag to observe any specific event. When that event occurs with respect to that specific HTML tag for which the event attribute is specified, this attribute will execute the function of the Javascript expression associated with it.

There are a few Event attribute types, which are dependent on the event kinds allowed by JavaScript. They are as follows:

  • Window Event Attributes
  • Keyboard Event Attributes
  • Form Event Attributes
  • ClipBoard Event Attributes
  • Media Event Attributes
  • Mouse Event Attributes
  • Drag Event Attributes

Let us go over each of the categories listed above in detail one by one.

Window Event Attributes Window Events are events that are associated with the window object and apply to the HTML tag.

AttributeValueDescription
onafterprintscriptExecutes the script after the file is printed.
onbeforeprintscriptExecutes the script before the file is printed.
onbeforeunloadscriptExecutes the script before a file is unloaded.
onerrorscriptExecutes the script when an error occurs.
onhashchangescriptExecutes the script when the anchor element in the URL of the website is changed.
onloadscriptExecutes the script when the website is completely loaded.
onmessagescriptExecutes the script when a message event occurs.
onofflinescriptExecutes the script when the community connection is disconnected and the browser starts running offline.
ononlinescriptExecutes the script when the browser starts running online.
onpagehidescriptExecutes the script when the modern website is hidden, such as though the consumer has moved away from the current website.
onpageshowscriptExecutes the script when the modern website is focused.
onpopstatescriptExecutes the script when the window's lively records are changed.
onresizescriptExecutes the script while the window is resized.
onstoragescriptExecutes the script while updating the web storage.
onunloadscriptExecutes the script while the current website is unloaded or the window is closed.

Keyboard Event Attributes Keyboard Events are those that happen when a user interacts with the keyboard.

AttributeValueDescription
onkeydownscriptThis event occurs when a user is pressing a key.
onkeypressscriptThis event occurs when a user presses a key.
onkeyupscriptThis event occurs when a user releases a key.

Form Event Attributes Form Events are HTML events that occur when a user interacts with form controls.

AttributeValueDescription
onblurscriptThis function is executed when the element loses attention.
onchangescriptThis event occurs when the element's value is modified.
oncontextmenuscriptThis script is performed when a context menu is executed.
onfocusscriptThis event occurs when the element is focused
oninputscriptThis script is executed when an element receives user input.
oninvalidscriptThis script is executed when an element is invalid.
onresetscriptThis event occurs when a form's Reset button is clicked.
onsearchscriptThis event occurs when a user types something into a search form (for input="search">).
onselectscriptExecutes when some text in an element is selected.
onsubmitscriptExecutes when some text in an element is selected. 

ClipBoard Event Attributes ClipBoard Events are events that occur when the clipboard is modified, such as copy, cut, and paste.

AttributeValueDescription
oncopyscriptThis event occurs when the user copies the content of an element.
oncutscriptThis event occurs when the user cuts the content of an element.
onpastescriptThis event occurs when the user pastes some content in an element.

Media Event Attributes Media Events are events that occur during the handling of media elements embedded within HTML documents, such as the <audio>, <video>, and <embed> tags.

AttributeValueDescription
onabortscriptScript to be executed on abort.
oncanplayscriptScript to be executed when a file is ready to play (when it has buffered enough to begin)
oncanplaythroughscriptScript that will be executed when a file can be played all the way through without halting for buffering.
oncuechangescriptScript that will be executed when the cue changes in an <track> element.
ondurationchangescriptScript that will be executed when the length of the media changes.
onemptiedscriptScript that will be executed when anything bad happens and the file becomes abruptly unavailable. (like unexpectedly disconnects)
onendedscriptScript that will be executed when the media has reached its conclusion (a useful event for messages like "thanks for listening")
onerrorscriptScript that will be executed if an error occurs while loading the file.
onloadeddatascriptScript to be executed when media data is received.
onloadedmetadatascriptScript that will be executed when meta data (such as dimensions and duration) are loaded.
onloadstartscriptExecute this script just as the file begins to load before anything is loaded.
onpausescriptScript that will be executed when the media is paused, either manually or automatically.
onplayscriptScript to be executed when the media is ready to start playing.
onplayingscriptScript that will be executed once the media has started playing.
onprogressscriptScript that will be executed while the browser retrieves media data.
onratechangescriptScript that will be executed whenever the playback rate changes (for example, when the user selects slow motion or fast forward mode)
onseekedscriptScript that will be executed when the seeking property is set to false. It denotes that the search has come to an end.
onseekingscriptScript to be executed when the seeking attribute is set to true. It indicates that seeking is active.
onstalledscriptScript to be executed when the browser is unable to retrieve the media data for whatever reason.
onsuspendscriptScript that is supposed to be executed when requesting the media data is interrupted before it is completely loaded for whatever reason.
ontimeupdatescriptScript that will be executed when the playing position changes (like when the user skips to a different part of the video)
onvolumechangescriptScript that will be executed each time the volume is altered (includes setting the volume to "mute")
onwaitingscriptScript that will be executed when the media has been halted but is expected to resume (like when the media pauses to allow more data to be buffered)

Mouse Event Attributes Mouse events are those that occur when a user interacts with a pointing device, such as a mouse.

AttributeValueDescription
onclickscriptThis event occurs when the mouse clicks on the element.
ondblclickscriptThis event occurs when the mouse double-clicks on the element.
onmousedownscriptExecutes when the mouse button is pressed on the element.
onmousemovescriptThis event occurs when the mouse pointer hovers over an element.
onmouseoutscriptThis event occurs when the mouse moves outside the element.
onmouseoverscriptThis event occurs when the mouse moves over the element.
onmouseupscriptExecutes when the mouse button is released.
onmousewheelscriptDeprecated. Make use of the onwheel attribute.
onwheelscriptThis event occurs when the mouse wheel rolls up or down on the element.

Drag Event Attributes Drag events are fired every few hundred milliseconds as a user drags an element or text selection.

AttributeValueDescription
ondragscriptThis event occurs when an element is dragged.
ondragendscriptScript to be executed after the completion of a drag operation.
ondragenterscriptThis script is executed when an element is dragged to a proper drop target.
ondragleavescriptThis script is executed when an element exits a valid drop target.
ondragoverscriptThis script is executed when an element is dragged over a valid drop target.
ondragstartscriptScript that is executed at the start of a drag operation.
ondropscriptScript that will be executed when a dragged element is dropped.
onscrollscriptScript that will be executed when an element's scrollbar is scrolled.

Misc Event Attributes

AttributeValueDescription
ontogglescriptThis event occurs when the user opens or closes the <details> element.

What is the <th> Tag in Html Used For?

The <th> tag in html is used to specify the header cell of a table. There are two types of cells in an HTML table:

  • Header Cell: This cell stores the header information (created with the help of <th> element)
  • Standard Cell: This cell stores the body of data (created with the help of <td> element)

The operation of both tags (<th> and <td> is somewhat the same, but the text characteristics are different. Text in <th> is bold and centered by default, but text in <td> is regular and left aligned by default.

Examples

Example 1: The header cells in the first row are marked up with the <th> element in the table below.

Output th-tag-html-example-1-output-code

Example 2: How to align content inside the <th> tag?

You can use the Align attributes to <td> tags to alter the alignment of the contents of a single cell. The Align feature allows you to align your information horizontally within the Cell in three ways: left, right, and center.

Output th-tag-html-example-2-output

Example 3: How to vertically align the content inside the <th> tag in html and set the height of a table header cell?

You can use the VAlign attributes to <td> tags to alter the alignment of the contents of a single cell. The VAlign feature allows you to place your information vertically within the cell in four different ways: Top, Bottom, Middle, and Baseline.

Output example-3-th-tag-html-output

Example 4: How to specify no word-wrapping in table header cell?

The contents of the table are very likely to modify the structure or dimensions of the table. For example, long words in table cells can cause the cell width to expand. If you fix that problem, the long words may cross the cell boundaries. To avoid this, we employ CSS's white-space property. This property forces the contents of <th> to be displayed in a single line.

Output example-4-th-tag-html-output

Example 5: How to set the width of a table header cell?

Use the CSS style to specify the width and height of the cell. HTML5 does not support the height and width attributes of the <td> cell. Just keep in mind that the use of the style attribute overrides any global style defined.

Output th-tag-html-example-5-output

Example 6: How to create table headers?

Use the <th> tag in html to construct a table header. The table row <tr> surrounds a table header tag. The <table> tag surrounds the <tr> tag.

Output th-tag-html-example-6-output

Example 7 to add background color to the table header cell?

A table header is white by default. You can change the color of the Table header by inserting CSS code. You can use bgcolor attribute to change the color of the table header.

Output example-7-tg-tag-output

Example 8: How to create a table with a caption?

The caption tag is used to specify a table's caption. This tag will be added just after the <table> tag. For each table, only one caption can be specified. It is by default aligned to the center.

Output example-8-th-tag-html-output

Example 9: How to define table cells that span more than one row or one column?

In HTML, the rowspan and colspan attributes specify how many rows or columns a cell should span. That is, if a row spans two rows, it will take up two rows of space in the table. It permits a single table cell to span more than one column or row in height.

Output example 9 th tag html output

Browser Support:

The <th> tag is supported by the following browsers:

  • Chrome
  • Android
  • Firefox (Gecko)
  • Firefox Mobile (Gecko)
  • Internet Explorer (IE)
  • Edge Mobile
  • Opera
  • Opera Mobile
  • Safari (WebKit)
  • Safari Mobile

Conclusion

  • The <th> tag in HTML identifies table cells that hold column header values rather than table data.
  • Nesting multiple <th> values in a parent <tr> element results in a row of table header values.
  1. table
  2. tr
  3. td
  4. tfoot