HTML Easy

Practical SQL course for Product Managers, Marketers, Designers, Software Engineers, CEOs and more. Learn with hundreds of bite-sized exercises which could be applied in real job right away.

HTML <table> Tag: Usage, Attributes, and Practical Examples

If you’re looking to create structured data within your webpage, the HTML <table> tag is an invaluable tool in your coding toolbox. By defining a table in HTML, you can organize information into rows and columns, making it easier for users to process complex data. It’s one of those fundamental elements that remains as crucial today as it was when first introduced.

The <table> tag comes with a host of attributes that enhance its functionality, allowing you to adjust the table’s appearance and behavior. Whether you’re looking to set borders, align cells or control spacing between cells – there’s likely an attribute for that!

To fully grasp how this essential HTML element works, we’ll delve into its usage and attributes before exploring some practical examples. This way, you’ll gain comprehensive knowledge on how to effectively use the HTML <table> tag in your web development projects. Buckle up because we’re about to dive deep into the world of tables!

Understanding the HTML <table> Tag

Diving right into the world of web development, I’m geared up to unravel one of the most commonly used HTML tags, the <table> tag. This power-packed element is a cornerstone in arranging data neatly and understandably on web pages.

The HTML <table> tag is primarily used for displaying tabular data. Think of it as creating an Excel spreadsheet right on your webpage! It’s all about rows and columns, housing data in a structured format. The neat separation of information makes it easier for users to digest complex data.

Here’s a simple example:

In this basic table structure:

  • The <table> tag encloses everything.
  • Each row is defined by <tr> (table row).
  • Within each row ( <tr> ), individual cells are represented by <td> (table data).

Getting creative with tables isn’t off-limits either. With additional attributes like colspan , rowspan , and others you can merge cells horizontally or vertically. Here’s how you’d use them:

It’s worth noting that while tables provide excellent structure, they aren’t meant for layout design. That’s a common mistake many rookies make. Rely on CSS Grid and Flexbox for your layout needs instead!

Finally, remember that the <table> tag is an in-line element by default, but can be turned into a block-level element using CSS. This means it will fall in line with other elements on the page unless you specify otherwise.

So there you have it – a quick dive into the versatile world of HTML tables. Armed with this knowledge, I hope you’ll create more organized, user-friendly web pages!

Key Attributes of the HTML <table> Tag

Diving straight into the nitty-gritty, let’s start with an attribute that’s fundamental to HTML table creation: border . This attribute dictates whether your table will have borders or not. You can set its value as 0 for no border, and any other number for the border width in pixels.

Next up is the cellpadding attribute. I’ve often found this one to be a real game changer when it comes to presentation. It specifies the space between cell walls and their content. If you want a roomier feel inside your cells, bump up this number!

Another key attribute we can’t overlook is cellspacing . Ever wanted some breathing room between your cells? That’s what cellspacing is for! It defines the space between table cells.

Now, for those of us keen on alignment perfection, there’s the align attribute which helps position your table on the page. The values could be “left”, “center” or “right”.

Lastly but certainly not least important is the width and height attributes. These control exactly what you’d expect – how wide and tall your table will be.

Remember these are just some examples of how you might use these attributes. I encourage you to experiment with different combinations to find what works best for your specific needs! And while it may seem daunting at first, practice makes perfect – before long, you’ll be creating tables like a pro! I’m sure you’ve stumbled upon websites and marveled at the organization of data displayed. Behind this clean layout is a simple yet powerful HTML tag called <table>. Here, I’ll guide you through using this essential tag, step by step.

First things first, the basic structure of an HTML table begins with <table> and ends with </table> . Within these tags are where the magic happens. To create rows in your table, use the <tr> tag (table row). Each cell within that row is defined using the <td> (table data) tag. It’s like shaping clay – one piece at a time!

Here’s an example:

In this snippet, we’ve created a table with one row and two cells. But what if we need more than just plain text? That’s where attributes come into play. You can add color to your cells using bgcolor attribute or align your text with align attribute. For instance:

Now you have a yellow row with center-aligned text in first cell! Pretty cool, right?

While working on tables though, it’s common to make mistakes such as forgetting to close tags or mismatching them altogether. Always remember: for every opening tag there should be a closing one.

Lastly but importantly, don’t forget about accessibility while creating tables – use <th> (table header) for headings and consider adding scope attribute to help screen readers understand content better.

The world of HTML tables isn’t limited to these basics; there are countless possibilities when you delve deeper. But with these steps, you’re on your way to creating amazing data layouts – one table at a time!

Real-world Examples of HTML <table> Tag Usage

Let’s dive right in and explore some real-world examples of how the HTML <table> tag is used. It’s a versatile tool that web developers frequently use, but it’s often overlooked by beginners.

Imagine you’re creating a website for a local bakery. They have an array of delicious breads and pastries they want to showcase online with their prices. Here’s where the HTML <table> tag comes into play! You can create a simple yet effective price list using this code:

In this example, we’ve used <tr> to create table rows, <th> for the table headers “Bread” and “Price”, and <td> for each data cell.

A common mistake I’ve noticed among beginners is forgetting to close tags or incorrectly nesting them. The structure should always follow: <table><tr><td></td></tr></table> . Any variation from this could lead to unexpected results or errors in your webpage layout.

Beyond simple text and number tables, you can also insert images within table cells. Imagine building a portfolio site as a photographer – you might want to display your photos in an organized grid format with captions. This could be achieved as follows:

In this case, we’re using the <img src> tag inside the <td> tag to insert an image, followed by a line break ( <br> ) and a caption.

These are just two examples out of countless possible applications for HTML table tags. Whether you’re displaying numerical data, text, or images, these tags offer a straightforward method to organize and present information on your webpage. But remember – practice makes perfect! Don’t be discouraged by initial mistakes; even experienced developers occasionally overlook a closing tag or mismatch their nests.

Conclusion: Mastering the HTML <table> Tag

In our deep dive into HTML’s <table> tag, we’ve covered its usage, key attributes, and even explored a few examples. I hope you now feel more confident to use this versatile tool in your website design toolkit.

Getting comfortable with the <table> tag can significantly enhance your webpage layouts. It’s particularly useful when it comes to organizing and displaying data in a neat and structured manner. Just remember these important points:

  • The essential structure of an HTML table starts with <table> and ends with </table>
  • Rows are created using the <tr> tag
  • Individual cells within those rows are made using the <td> (or “Table Data”) tag.

Here’s a quick example:

Common mistakes to avoid include forgetting to close tags or not nesting them properly. These errors can lead to unexpected results on your page layout.

I encourage you to continue practicing and experimenting with different attributes until you’re completely familiar with all that this valuable HTML element has to offer. Happy coding!

table tag assignment in html

Cristian G. Guasch

Related articles.

  • HTML <dd> Tag: Usage, Attributes, and Real-World Examples
  • HTML <small> Tag: Usage, Attributes, and Practical Examples
  • HTML <noframes> Tag: Usage, Attributes, and Real-World Examples
  • HTML <meter> Tag: Use with Practical Examples
  • HTML <isindex> Tag: Usage, Attributes, and Real-World Examples
  • HTML <map> Tag: Usage, Attributes, and Real-World Examples
  • HTML <iframe> Tag: Usage, Attributes, and Examples
  • HTML <figcaption> Tag: Usage, Attributes, and Practical Examples
  • HTML <rt> Tag: Usage, Attributes, and Real-World Examples
  • HTML <summary> Tag: Functions, Attributes, and Real-Life Examples
  • HTML <video> Tag: Usage, Attributes, and Real-World Examples
  • HTML <button> Tag: Usage, Attributes, and Real-World Examples
  • HTML <base> Tag: Usage, Attributes, and Real-Life Examples
  • HTML <template> Tag: Usage, Attributes and Real-World Examples
  • HTML <xmp> Tag: Usage, Attributes and Practical Examples
  • HTML <menuitem> Tag: Usage, Attributes, and Examples
  • HTML <body> Tag: Usage, Attributes and Real-World Examples
  • HTML <area> Tag: Usage, Attributes, and Examples with Ease
  • HTML <nobr> Tag: Usage, Attributes and Examples
  • HTML <colgroup> Tag: Usage, Attributes, and Examples
  • HTML <frame> Tag: Usage, Attributes, and Practical Examples
  • HTML <!DOCTYPE> Tag: Usage, Attributes, and Real-World Examples
  • HTML <details> Tag: Uses, Attributes, and Real-World Examples
  • HTML <datalist> Tag: Practical Usage, Intriguing Attributes, and Real-World Examples
  • HTML <output> Tag: Practical Examples and Attributes
  • HTML <header> Tag: Your Guide to Using It Effectively with Examples
  • HTML <samp> Tag: Usage, Attributes, and Real-World Examples
  • HTML <em> Tag: Usage, Attributes, and Real-World Examples
  • HTML <applet> Tag: Usage, Attributes, and Real-World Examples
  • HTML <br> Tag: Unraveling Its Usage, Attributes, and Real-Life Examples
  • HTML <del> Tag: Usage, Attributes, and Practical Examples
  • HTML <section> Tag: Usage, Attributes, and Real-World Examples
  • HTML <td> Tag: Usage, Attributes, and Real-World Examples
  • HTML <figure> Tag: Use Cases and Examples
  • HTML <center> Tag: Uses with Practical Examples
  • HTML <img> Tag: Usage, Attributes, and Real-World Examples
  • HTML <article> Tag: Uses, Attributes and Examples
  • HTML <noscript> Tag: Usage, Attributes, and Real-World Examples
  • HTML <bdo> Tag: Usage, Attributes, and Examples
  • HTML <legend> Tag: Usage, Attributes, and Practical Examples
  • HTML <dfn> Tag: Usage, Attributes and Real-World Examples
  • HTML <ruby> Tag: Usage, Attributes, and Real-World Examples
  • HTML <rb> Tag: Usage, Attributes and Practical Examples
  • HTML <data> Tag: Usage, Attributes, and Practical Examples
  • HTML <main> Tag: Usage and Examples
  • HTML <cite> Tag: Usage, Features, and Real-Life Scenarios
  • HTML <embed> Tag: Uses, Attributes, and Real-Life Examples
  • HTML <dt> Tag: Usage and Examples
  • HTML <menu> Tag: Usage, Attributes, and Examples
  • HTML <blockquote> Tag: Practical Uses and Handy Examples

Popular Tutorials

Learn python interactively, popular examples.

  • Introduction
  • What is HTML?

HTML Basics

  • HTML Web Design Basics
  • HTML Paragraphs
  • HTML Headings
  • HTML Comments

HTML Unordered List

  • HTML Ordered List
  • HTML Description List
  • HTML Line Break
  • HTML Pre Tag
  • HTML Horizontal Line

HTML Inline

  • HTML Block and Inline
  • HTML Images
  • HTML Italic
  • HTML Superscript and Subscript
  • HTML Formatting
  • HTML Meta Elements
  • HTML Favicon
  • HTML Form Elements
  • HTML Form Action

Semantic HTML

  • HTML Semantic HTML
  • HTML div Tag
  • HTML aside Tag
  • HTML section Tag
  • HTML footer Tag
  • HTML main Tag
  • HTML figure and figcaption
  • HTML Accessibility

HTML, CSS & JavaScript

  • HTML Layout
  • HTML Responsive Web Design
  • HTML and JavaScript

Graphics & Media

  • HTML Canvas

HTML Miscellaneous

  • HTML Iframes
  • HTML Entities
  • HTML Quotations
  • HTML File Paths
  • HTML Emojis
  • HTML Symbols

Web Tutorials

CSS Table Styling

The HTML table tag ( <table> ) is used to represent data in a structured way by creating a table. For example,

Browser Output

HTML table with multiple rows of data.

In the above example, you can see we have used multiple tags to create a table in HTML.

  • <table>

Table tag <table> in HTML

The <table> tag is used to define a table. For example,

Table Row <tr> in HTML

The <tr> tag is used to define a row in a table. For example,

The table row can include either table heading, <th> or table data, <td> .

In a table, there can be any number of rows.

Table Heading, <th> in HTML

The <th> tag is used to define a table header. It is generally the top row of the table. For example,

HTML table with Table Headers

In the above example, Item and Count are table headers and they are used to represent the category of data in a particular row.

Here, the styling of the table headers is bold and center-aligned. This is because the <th> tag has some default styling.

Table Cell <td> in HTML

The <td> tag is used to define table cells (data). The table cells store data to be displayed in the table. For example,

In the above example, <td>Apple</td> , <td>Mango</td> and <td>Orange</td> are table cells.

Table cells are generally inside the table row or table headers.

  • Table Border

Remember we have used the border attribute in our first example.

In HTML, the border attribute is used to add a border to a table and all the cells.

HTML table with borders

Note: We can have borders of various styles in tables, however for more specific borders, we need to use CSS.

To prevent double borders like the one in the example above, we can set the border-collapse property of the table. For example,

HTML Table with collapsed border

  • Table Head, Body, and Footer

The HTML table can be divided into three parts: a header, a body, and a footer.

1. Table Header

We use the <thead> tag to add a table head. The <thead> tag must come before any other tags inside a table. For example,

The content of <thead> is placed on the top part of the table and we usually place the rows with table headers inside the <thead> tag.

2. Table Body

We use the <tbody> tag to add a table body. The <tbody> tag must come after <thead> and before any other tags inside a table. For example,

The content of <tbody> is placed on the center part of the table and we usually place the rows with the content we want to represent in the <tbody> .

3. Table Footer

We use the <tfoot> tag to add a table footer. The <tfoot> tag must come after <tbody> and before any other tags inside a table. For example,

The content of <tbody> is placed on the bottom part of the table and we usually place the rows with the footer in the <tfoot> .

All these tags must be placed inside a <table> tag and must contain at least one <tr> . For example,

Example: HTML Table Head, Body, and Footer

An HTML Table with a

  • Colspan and Rowspan

The colspan attribute merges cells across multiple columns. For example,

An HTML Table showcasing colspan

In the above example, you can see that the last row only has 2 cells with one cell occupying 2 columns.

The value of the colspan attribute determines how many columns the cell occupies.

The rowspan attribute merges cells across multiple rows. For example,

An HTML Table showcasing rowspan

In the above example, you can see that the first column only has 2 cells with one cell occupying 2 rows.

The value of the rowspan attribute determines how many rows the cell occupies.

Things to know about HTML Table

Yes, we can use both colspan and rowspan to create cells that occupy multiple rows and columns. Here is an example:

An HTML table showcasing rowspan and colspan

In this tutorial we have seen table headers, <th> , used in the top row multiple times. But we can also add the <th> tags across columns to create a vertical header. For example,

An HTML table with <th> elements on first cell of each row

The <caption> element acts as the title of the table. It is used to give a short description of the table. It shows up on top of the table.

The <caption> tag must be the first child of the <table> element.

An HTML table with a table caption

Table of Contents

  • Table tag in HTML
  • Table Row in HTML
  • Table Heading in HTML
  • Table Cell in HTML

Related Tutorials

Programming

All About HTML

  • Privacy Policy

All About HTML

A Comprehensive Guide to Tables in HTML5: Creating Structured Data

Table of contents, 1. introduction to tables in html, 1.1 what are tables in html.

HTML tables are a way to organize and display tabular data on a webpage. A table consists of rows and columns, forming a grid-like structure. Each cell within the table can contain data or other HTML elements. Tables provide a structured format for presenting data in a clear and organized manner.

1.2 Why Use Tables in HTML?

Tables in HTML are primarily used to present data in a structured way. They offer several benefits:

  • Data organization: Tables allow you to present data in a tabular format, making it easier for users to understand and analyze information.
  • Readability: Tables provide a clear visual representation of data, with rows and columns making it easy to compare and interpret values.
  • Accessibility: Tables can be made accessible to users with screen readers or other assistive technologies, improving the accessibility of tvhe information.
  • Compatibility: Tables are supported by all modern web browsers, ensuring consistent rendering of data across different platforms.
  • Versatility: Tables in HTML can be customized and styled using CSS to match the design of your website, making them versatile for various design needs.

1.3 Structure of an HTML Table

The structure of an HTML table consists of several key elements:

  • <table> : This is the container element that defines the table.
  • <tr> : Short for “table row,” this element represents a row within the table. It contains one or more table cells ( <td> or <th> ).
  • <td> : Stands for “table data,” this element represents a cell within a table row and contains the actual data.
  • <th> : Short for “table header,” this element represents a header cell within a table row. It is used to label or provide a heading for a column or row.
  • <caption> : This optional element is used to provide a caption or title for the table.

The structure is hierarchical, with <table> as the parent element, <tr> as the child elements, and <td> or <th> as the child elements of <tr> . The <caption> element, if used, is placed before the <tr> elements.

Here’s an example of a basic HTML table structure:

In this example, the table contains a caption, two header cells ( <th> ) for the column labels, and three rows ( <tr> ) with corresponding data cells ( <td> ) representing the month and revenue values.

The structure of an HTML table allows for flexibility in organizing and presenting data, making it a powerful tool for data representation on the web.

2. Creating Basic Tables in HTML

2.1 table element and table structure.

The <table> element is the main container for creating an HTML table. It defines the start and end of the table structure. All other table-related elements are nested inside the <table> element. Here’s an example of a basic table structure:

2.2 Table Headers and Table Data Cells

In an HTML table, the table headers and table data cells are defined using the <th> and <td> elements, respectively.

  • <th> : The <th> element is used to define a header cell in the table. It typically contains text or other content that represents the header of a column or row. By default, the text in a <th> cell is bold and centered. Here’s an example:
  • <td> : The <td> element is used to define a data cell in the table. It contains the actual data that corresponds to a specific row and column. Here’s an example:

2.3 Table Rows and Table Cells

Table rows are defined using the <tr> element, and they serve as containers for table cells. Each <tr> element represents a row in the table. Here’s an example:

In the above example, we have two rows, each containing two data cells.

2.4 Table Caption

The <caption> element is optional and is used to provide a caption or title for the table. It should be placed immediately after the opening <table> tag. Here’s an example:

The caption element is typically styled differently from the rest of the table to visually distinguish it as the title or description of the table.

By using these table-related elements in HTML, you can structure and organize your tabular data effectively, making it easier for users to understand and interpret the information presented in the table.

table tag assignment in html

3. Formatting and Styling Tables in HTML

3.1 adding borders and background colors.

You can add borders and background colors to your Tables in HTML using CSS. The border property allows you to define the thickness, style, and color of the table borders. The background-color property lets you specify the background color of the table or individual cells.

Here’s an example of adding borders and background colors to a table:

In the above example, the CSS code within the <style> tags sets the border-collapse property to collapse, which removes the spacing between cells. The th and td elements have borders with a thickness of 1 pixel and a solid black color. The th elements have a light gray background color (#f2f2f2), while the td elements have a white background color.

3.2 Adjusting Table Width and Height

To adjust the width and height of the table, you can use CSS properties such as width, height, and max-width. You can specify the dimensions in pixels, percentage, or other valid CSS units.

Here’s an example of adjusting the table width and height:

In the above example, the table’s width is set to 100% of its containing element, while the height is set to 200 pixels.

3.3 Aligning Table Content

You can align the content within table cells using CSS. The text-align property allows you to horizontally align the text, while the vertical-align property controls the vertical alignment of the content within cells.

Here’s an example of aligning table content:

In the above example, the text within table cells is centered horizontally using the text-align property, and vertically aligned to the middle using the vertical-align property.

3.4 Styling Table Headers and Table Cells

You can apply specific styles to table headers ( <th> ) and table cells ( <td> ) by targeting them with CSS selectors. This allows you to customize the appearance of headers and cells differently.

Here’s an example of styling table headers and cells:

In the above example, the table headers ( <th> ) have a light gray background color, black text color (#333), and bold font weight. The table cells ( <td> ) have a white background color, dark gray text color (#666), and the default font weight.

By using CSS to style your tables, you can customize their appearance to match the design of your website and improve the overall visual presentation of the table data.

4. Merging and Splitting Cells

4.1 rowspan and colspan attributes.

The rowspan and colspan attributes allow you to merge cells vertically (rowspan) or horizontally (colspan) within an HTML table. These attributes are useful when you want to create cells that span multiple rows or columns.

Here’s an example of using the rowspan and colspan attributes:

In the above example, the th element in the first row has a colspan of 2, which makes it span across two columns. The td element in the second row has a rowspan of 2, which makes it span across two rows. This allows you to create more complex table layouts and merge cells as needed.

4.2 Creating Header Groups and Data Groups

Tables in HTML provide the <thead> , <tbody> , and <tfoot> elements to group table headers and data. These elements help to structure the table and improve accessibility by separating the header, body, and footer sections.

Here’s an example of using header groups and data groups:

In the above example, the <thead> element contains the table headers, the <tbody> element contains the table data, and the <tfoot> element contains the table footer. This grouping makes it easier to style and manipulate the different sections of the table.

4.3 Nesting Tables in HTML

Tables in HTML can be nested within each other, which means you can place a table inside a table cell. This technique is useful when you need to create more complex table structures or display additional information within a cell.

Here’s an example of nesting Tables in HTML:

In the above example, a table is nested within the first cell of the outer table. This allows you to create a more intricate layout or present tabular data within a specific cell.

When nesting Tables in HTML, it’s important to keep in mind the overall structure and ensure that it remains clear and readable. Too much nesting or complexity can make the table harder to understand and maintain.

5. Adding Headers and Footers

5.1 table head (<thead>).

The <thead> element is used to define the header section of an HTML table. It is typically placed before the <tbody> element and contains one or more <tr> (table row) elements that represent the header row(s) of the table.

Here’s an example of using the <thead> element:

In the above example, the <thead> element contains a single <tr> element that defines the header row. The <th> elements inside the header row represent the individual header cells.

The purpose of the <thead> element is to group the table headers together and provide a clear distinction between the header section and the body section of the table. This helps with styling, accessibility, and maintaining a well-structured HTML document.

5.2 Table Body (<tbody>)

The <tbody> element is used to define the body section of an HTML table. It contains one or more <tr> (table row) elements that represent the data rows of the table.

Here’s an example of using the <tbody> element:

In the above example, the <tbody> element contains multiple <tr> elements that define the data rows of the table. The <td> elements inside the data rows represent the individual data cells.

The purpose of the <tbody> element is to group the table data together and separate it from the header section. It helps with styling, scripting, and improving the structure and semantics of the HTML table.

5.3 Table Foot (<tfoot>)

The <tfoot> element is used to define the footer section of an HTML table. It is placed after the <tbody> element and contains one or more <tr> (table row) elements that represent the footer row(s) of the table.

Here’s an example of using the <tfoot> element:

In the above example, the <tfoot> element contains a single <tr> element that defines the footer row. The <td> elements inside the footer row represent the individual footer cells.

The purpose of the <tfoot> element is to group the table footer together and separate it from the header and body sections. It is typically used to display summary information or additional details related to the table data.

6. Creating Complex Tables in HTML

6.1 nested tables for complex structures.

Nested tables refer to the practice of placing one table inside another table to create complex structures. This can be useful when you need to represent hierarchical or multi-dimensional data. By nesting tables, you can organize and present data in a more structured and visually appealing manner.

Here’s an example of a nested table:

In the above example, there is an outer table with two columns. The first column contains a nested table with two rows and two columns. This allows for a more complex arrangement of data.

It’s important to use nested Tables in HTML judiciously and consider the readability and accessibility of the content. Excessive nesting can make the table structure difficult to understand and navigate, especially for screen readers and assistive technologies.

6.2 Grouping Related Data with <tbody>

The <tbody> element, as mentioned earlier, is used to group the body section of an HTML table. In addition to organizing data rows, it can also be used to group related data within a table. This helps improve the structure and semantics of the table, making it easier to understand and maintain.

Here’s an example of using <tbody> to group related data:

In the above example, two <tbody> elements are used to group related data. The first <tbody> contains data for two products, while the second <tbody> contains data for two different products. This grouping makes it clear that each <tbody> represents a distinct set of data.

Using <tbody> in this way not only improves the structure but also allows for easier styling and scripting of specific sections of the table.

6.3 Sorting and Filtering Tables in HTML with JavaScript

JavaScript can be used to enhance the functionality of HTML tables by enabling sorting and filtering capabilities. By adding interactive features, users can manipulate the table data dynamically, making it easier to find information and analyze the data.

There are various JavaScript libraries and frameworks available that provide pre-built table sorting and filtering functionalities, such as DataTables, SortableJS, and List.js. These libraries allow you to add sorting arrows to table headers, implement search boxes for filtering, and customize the behavior and appearance of the table.

Here’s an example of using the DataTables library to add sorting and filtering to a table:

In this example, the DataTables library is included, and the table with the id “myTable” is initialized as a DataTable. This automatically adds sorting and search functionality to the table.

By incorporating JavaScript libraries or writing custom scripts, you can create more interactive and dynamic tables that enhance the user experience and allow for efficient data manipulation.

7. Accessible Tables in HTML

7.1 providing table summaries.

To improve accessibility, it is recommended to provide a summary for your table using the <summary> element. The summary should briefly describe the purpose and structure of the table, making it easier for screen reader users to understand the content.

Here’s an example of providing a table summary:

In this example, the <summary> element is used within a <details> element to provide a summary for the table. The screen reader will announce the summary to the user, giving them an overview of the table’s purpose.

7.2 Adding Row and Column Headers

To improve table accessibility, it’s important to associate row and column headers with the appropriate cells. This allows screen readers to provide context when reading the table data.

You can use the <th> element for table headers and the scope attribute to define the relationship between the headers and data cells. The scope attribute can have two values: “row” for row headers and “col” for column headers.

Here’s an example of adding row and column headers:

In this example, the first row contains column headers with the scope="col" attribute, indicating that they represent column headers. The first column in the body contains row headers with the scope="row" attribute, indicating that they represent row headers.

By using appropriate headers and associating them correctly with the data cells, you enhance the accessibility and usability of the table.

7.3 Using ARIA Roles and Attributes

ARIA (Accessible Rich Internet Applications) roles and attributes can be used to further enhance the accessibility of tables. ARIA provides additional information and context to assistive technologies when interacting with the table.

Here are some commonly used ARIA roles and attributes for Tables in HTML:

  • role="table" : Specifies that an element represents a table.
  • role="rowgroup" : Groups a set of rows together, such as <thead> , <tbody> , and <tfoot> .
  • role="row" : Specifies that an element represents a row.
  • role="columnheader" : Specifies that an element represents a column header.
  • role="rowheader" : Specifies that an element represents a row header.
  • aria-labelledby : Associates an element with a label by referring to the ID of the labeling element.

Here’s an example of using ARIA roles and attributes:

In this example, the table is represented using <div> elements with appropriate ARIA roles. The aria-labelledby attribute is used to associate the column headers with their respective labels using unique IDs.

By using ARIA roles and attributes, you provide additional information to assistive technologies, making the table more accessible to users with disabilities.

7.4 Testing Table Accessibility

It is crucial to test the accessibility of your Tables in HTML to ensure they are usable by everyone, including users with disabilities. Here are some approaches and tools you can use to test table accessibility:

  • Manual Testing: Review your table with keyboard navigation and a screen reader to assess its structure, content, and relationships. Verify that the table makes sense when read aloud and that the headers are properly associated with the data cells.
  • WAVE Web Accessibility Evaluation Tool: WAVE is a free online tool that provides feedback on the accessibility of web content. It can help identify any accessibility issues in your tables and provide suggestions for improvements.
  • Lighthouse Accessibility Audit: Lighthouse is a built-in auditing tool in the Chrome browser that can perform an accessibility audit of your web page. It can identify accessibility issues, including those related to Tables in HTML, and provide recommendations for fixes.
  • Screen Readers: Test your table with popular screen readers like NVDA (NonVisual Desktop Access), JAWS (Job Access With Speech), or VoiceOver (built into macOS and iOS). Listen to how the table is read and ensure it conveys the intended information and structure.

By performing thorough accessibility testing, you can identify and address any issues in your tables, ensuring they are accessible to all users.

8. Responsive Tables

8.1 responsive design principles.

Responsive design is an approach to web design that aims to create websites and applications that provide optimal viewing and interaction experiences across different devices and screen sizes. Here are some key principles of responsive design:

Fluid Grids: Use relative units like percentages instead of fixed units like pixels to create flexible and fluid layouts. This allows the content to adapt and resize based on the screen size.

Flexible Images: Ensure that images can resize and scale proportionally based on the available space. Use CSS techniques like max-width: 100% to prevent images from overflowing their containers.

Media Queries: Apply CSS rules based on the characteristics of the device, such as screen size, resolution, and orientation. Media queries allow you to define different styles for different breakpoints, ensuring optimal presentation on various devices.

Mobile-First Approach: Start designing and developing for mobile devices first, then progressively enhance the layout and functionality for larger screens. This approach ensures a solid foundation for smaller screens and simplifies the process of scaling up.

Content Priority: Prioritize important content and functionality for smaller screens, and consider hiding or reorganizing less critical elements. This ensures that the most relevant information is readily accessible on smaller devices.

8.2 CSS Techniques for Responsive Tables

Tables can be challenging to make responsive due to their inherent tabular structure. However, there are CSS techniques you can use to improve the responsiveness of tables:

Horizontal Scrolling: Apply overflow-x: auto to the table container to enable horizontal scrolling on smaller screens. This allows users to swipe horizontally to view the entire table.

Stacking Rows: Use media queries to change the display property of table rows from table-row to block or flex on smaller screens. This causes the rows to stack vertically, making them easier to read and navigate.

Collapsible Rows: Implement a “accordion” pattern where only the first column of the table is visible, and clicking on a row expands it to reveal additional columns. This technique saves space and improves readability on smaller screens.

8.3 Using Media Queries for Responsive Tables in HTML

Media queries are a key component of responsive design and allow you to apply different CSS styles based on the characteristics of the device. Here’s how you can use media queries to make tables responsive:

Define Breakpoints: Determine the breakpoints or screen sizes at which you want your table to adapt. Common breakpoints include small screens (e.g., smartphones), medium screens (e.g., tablets), and large screens (e.g., desktops).

Write Media Queries: Use the @media rule in CSS to define specific styles for different breakpoints. For example:

Apply Responsive Styles: Within each media query, write CSS rules to modify the table’s appearance, such as adjusting font sizes, changing column widths, or altering the layout. Use CSS techniques like stacking rows or horizontal scrolling to optimize the table’s presentation for different screen sizes.

By utilizing media queries, you can customize the styling and layout of your table based on the device’s screen size, ensuring a responsive and user-friendly experience.

9. Advanced Table Features

9.1 table sorting and filtering with javascript libraries.

JavaScript libraries provide powerful tools for adding sorting and filtering functionality to Tables in HTML. These libraries simplify the process of implementing these features and enhance the user experience. Here are a few popular JavaScript libraries for table sorting and filtering:

  • DataTables: DataTables is a widely used library that provides extensive options for sorting, filtering, and pagination. It offers various built-in features like multi-column sorting, search functionality, and customizable styling.
  • List.js: List.js is a lightweight library that allows you to add sorting, filtering, and live searching to HTML tables. It provides an intuitive API and supports various customization options.
  • Isotope: Isotope is a versatile library primarily used for filtering and sorting items, but it can also be applied to tables. It offers a smooth filtering experience with options for combining filters and animated transitions.

These libraries typically require you to include the library’s JavaScript and CSS files and initialize the table with specific configurations. They often provide APIs to programmatically control the sorting and filtering behavior.

9.2 Adding Pagination to Large Tables

When dealing with large Tables in HTML, it’s important to consider adding pagination to improve performance and user experience. Pagination divides the table into multiple pages, displaying a portion of the data at a time. Here’s how you can implement pagination for large tables:

  • Determine the number of rows to display per page. This can be based on the available screen space or user preferences.
  • Calculate the total number of pages by dividing the total number of rows by the number of rows per page.
  • Create a navigation mechanism, such as numbered buttons or next/previous links, to allow users to navigate between pages.
  • Implement logic to display the appropriate rows for the current page and hide the remaining rows.
  • Update the pagination controls dynamically based on user interactions or changes to the table’s data.

JavaScript libraries like DataTables and List.js mentioned earlier also offer built-in pagination functionality, making it easier to implement pagination for your tables.

9.3 Table Exporting and Importing

Table exporting and importing features allow users to save table data locally or import data into a table from external sources. Here are some common techniques for implementing table exporting and importing:

  • Exporting: Provide a button or link that triggers the export process. When clicked, generate a downloadable file (such as CSV, Excel, or PDF) containing the table data. This can be done using server-side technologies or JavaScript libraries dedicated to exporting data.
  • Importing: Allow users to upload a file (such as CSV or Excel) containing table data. Parse the uploaded file and populate the table with the imported data. This can be done using server-side technologies or JavaScript libraries that support file parsing.

There are also JavaScript libraries available that provide comprehensive functionalities for table exporting and importing, such as Papa Parse for CSV parsing and jsPDF for PDF generation.

Implementing table exporting and importing features can enhance the usability and flexibility of your tables, enabling users to work with table data in their preferred formats.

10. Best Practices for Using Tables

Tables are a powerful tool for organizing and presenting data in HTML. To ensure the best user experience and accessibility, here are some best practices to follow when using tables:

10.1 When to Use Tables in HTML

Tables should be used when you have tabular data that requires a structured representation. They are ideal for displaying data that has rows and columns with a clear relationship, such as financial data, comparative data, or data grids. Avoid using tables for layout purposes or to create complex designs.

10.2 Structuring Data Effectively

When structuring data in tables, consider the following guidelines:

  • Use header cells: Each column should have a header cell (<th>) that describes the content of the column.
  • Use scope attribute: For complex tables, use the “scope” attribute to associate header cells with the corresponding data cells. This helps assistive technologies understand the relationships within the table.
  • Use semantic markup: Use appropriate HTML tags to convey the meaning of the content. For example, use <strong> or <em> tags for emphasis, and <abbr> for abbreviations.
  • Group related data: Use <tbody> to group rows that share a common relationship, such as grouping rows by category or subheading.

10.3 Enhancing Table Accessibility

To improve the accessibility of Tables in HTML, consider the following practices:

  • Provide table summaries: Use the <caption> element to provide a summary or description of the table’s content. This helps screen reader users understand the purpose and structure of the table.
  • Use row and column headers: Use the “scope” attribute or the <th> element to define row and column headers. This allows screen readers to associate the header cells with their respective data cells.
  • Add alternative text: If the table contains images or icons, provide descriptive alternative text to ensure that users with visual impairments can understand the content.
  • Test with assistive technologies: Use screen readers and other assistive technologies to test the table’s accessibility and ensure it can be navigated and understood by users with disabilities.

10.4 Optimizing Table Performance

To optimize table performance, consider the following tips:

  • Minimize the number of rows and columns: Large tables can impact page loading and performance. Consider paginating or implementing lazy loading techniques for tables with a large amount of data.
  • Use proper table markup: Use semantically correct HTML tags to structure the table. Avoid using unnecessary nested tables or excessive styling that can affect performance.
  • Optimize images and media: If your table includes images or media, optimize their file sizes to reduce load times. Use appropriate image formats and compression techniques.
  • Implement server-side processing: For tables with dynamic data or complex calculations, consider offloading some processing to the server to improve performance.
  • Test and measure performance: Use browser development tools and performance testing tools to assess the table’s impact on page load times and identify areas for optimization.

By following these best practices, you can ensure that your tables are well-structured, accessible, and optimized for performance, providing a better user experience for your audience.

11. Conclusion

In conclusion, tables in HTML are a versatile and powerful tool for organizing and presenting tabular data on the web. By understanding the structure, syntax, and best practices for using tables, you can create well-structured, accessible, and visually appealing tables that effectively convey information to your users.

Throughout this blog post, we covered various aspects of working with tables in HTML. We explored the basics of table elements, such as the table, tr, th, and td tags, and learned how to structure tables with headers, data cells, rows, and captions. We also discussed techniques for styling tables, adding borders and background colors, adjusting table width and height, and aligning table content.

Furthermore, we delved into advanced topics such as rowspan and colspan attributes, creating header groups and data groups, and nesting tables for complex structures. We also explored techniques for enhancing table accessibility, including providing table summaries, adding row and column headers, and using ARIA roles and attributes.

We discussed responsive design principles for tables and demonstrated CSS techniques for making tables responsive, adapting to different screen sizes and devices. We also examined how media queries can be used to modify table styles based on viewport dimensions.

Additionally, we explored advanced features like table sorting, filtering, pagination, and exporting/importing data. We saw how JavaScript libraries can be leveraged to enhance table functionality and user interactions.

Throughout the blog post, we emphasized the importance of best practices when using tables. We discussed when to use tables and when to consider alternative approaches, the significance of structuring data effectively, enhancing table accessibility for users with disabilities, and optimizing table performance to ensure smooth user experiences.

By following these best practices and understanding the capabilities of tables in HTML, you can create well-organized, accessible, and visually appealing tables that effectively present data to your users. Whether you’re working with simple data tables or complex data grids, tables in HTML provide a robust and flexible solution for data representation on the web.

All About HTML

June 3, 2023

Previous Exploring the Power of the Video Tag in HTML: A Comprehensive Guide

Next mastering forms in html: a comprehensive guide to all form fields, related posts ....

A Comprehensive Guide to Tables in HTML5: Creating Structured Data

Simple Tips to Creating and Styling Responsive Tables in HTML5

table tag assignment in html

Exploring the Power of iframe tag in HTML5: A Comprehensive Guide

Mastering Forms in HTML: A Comprehensive Guide to All Form Fields

Mastering Forms in HTML: A Comprehensive Guide to All Form Fields

Leave a reply cancel reply.

Your email address will not be published. Required fields are marked *

HTML Tables: All there is to know about them

HTML Tables: All there is to know about them

by Alexander Gilmanov

1*UFIlBVRuLEGCGfliYgNwsA

Judging by the fact that we created wpDataTables , it’s no secret that we like tables. So much that we wrote this lengthy article about them to help out those of you who are beginners and want to learn about HTML tables.

HTML tables are used for displaying data that make sense in spreadsheet software. They consist of rows and columns and are often used on websites for the effective displaying of tabular data.

So how to make a table in HTML? When to use it and why? What are good HTML table examples? Today, we are going to answer these questions and more to help you understand everything there is to know about HTML tables.

Table of contents

Introduction to tables.

  • Table styling

HTML tables frequently asked questions

Html table generator tools.

The HTML table is used for arranging data (such as text, images, links etc.) into the tabular design — basically, rows and columns.

When to Use Tables

A table in HTML makes a lot of sense when you want to organize data that would look best in a spreadsheet. An HTML table is a great way to display things such as financial data, calendars, pricing, feature comparison, the nutrition facts information panel, bowling scores, and many other tabular data.

There is a chance you have heard that the tables were unsemantic. However, that is not at all true. Tables semantically indicate tabular data and they are the best choice for displaying data of this kind.

When NOT to Use Tables

While some data looks great in tables, there are things that shouldn’t be arranged that way simply because it wouldn’t make any sense. There are also some other inappropriate CSS table uses that should be avoided if possible.

For example, you should never use tables for layout . The thing is that table elements semantically describe tabular data and using them for other purposes is a breach of semantic duty.

The general rule is that the websites should be accessible. One part of accessibility is screen readers which read tables from top to bottom, left to right. With the tables in HTML, the order of how the site is presented is determined by visual choices instead of the accessibility choices. In cases like that, screen readers don’t always work as you’d want them to.

Table Elements

HTML tables usually come with a short description of their purpose. Sometimes, a more detailed description is provided via the summary attribute for the benefit of people using speech or Braille-based user agents.

Table rows may be grouped into a head, foot, and body sections, (via the THEAD , TFOOT and TBODY elements). User agents may exploit the head/body/foot division to support scrolling of body sections independently of the head and foot sections. When we print the long HTML tables, the head and foot information is usually displayed on each page containing the table.

If you want to provide more structural information, you can also group columns. In addition to that, column properties may be declared at the start of the table definition using the COLGROUP and COL elements.

Table cells contain the header information and/or data and they can span multiple columns and rows. When you label each cell with the HTML 4 table mode, the non-visual user agents can communicate the information to the user more easily. Not only is this useful for users with disabilities but it makes it possible for modal wireless browsers with limited display capabilities to handle HTML tables.

We mentioned already that tables HTML should not be used for layout. Instead, you should use style sheets whenever necessary to achieve better results and better accessibility.

Head and Body

Let’s take a look at a basic example of HTML table style:

Imagine looking at a row (horizontal) to see a single person and relevant information about them. When you look up and down a column (vertical), you will get a sense of the variety or pattern of data.

The first row is the header of the table and it contains no data — just the titles of the columns. You can semantically indicate that is the case with the <the ad> element, which would wrap the firs t <tr> (it could wrap as many rows as needed that are all header information).

When you use <the ad>, there must be n o <tr> that is a dire ct chil d of <table>. All rows must be within ei ther th e < ;thead& gt;, <tbody>, or <tfoot>.

Table Footer

Along with <the ad> ; and & lt;tbody> ;, ther e is <tfoot> for wrapping table rows that indicate the footer o f the t able. Like <thead>, best for semantically indicating that these are not data rows but ancillary information.

The placement of <tfo ot> is unique in HTML as it comes after & lt;thead> and be fore <tbody>! So even though it might seem logical to find it at the end of <table>, it is actually not the case. Since the footer contains information necessary to understand the table, it is placed before the data in the source order for better accessibility.

Table footer can be used in long HTML tables to repeat the header, for example. However, it can be used for other purposes as well, for instance, with a layout where the position of elements jumps around from bottom to top depending on needs.

Table Elements and their Attributes

<tfoot> html tag.

The <tfo ot> element identifies one or mor e <tr> elements as containing summary contents of a table’s c olumns. The <tfoot> element must be the direc t desce ndant of a <table> element.

In HTML5, <tfo ot> can be placed either before or after & lt;tb ody& gt; and <tr>elements, but must appear a ft er any < ;capti on>, <colgroup>, and <thead> elements.

<tbody> HTML Tag

The <tbo dy> element must be a direct descendant of a & lt;table> element and is used to i dentify <tr> elements that comprise the body of the table. The <tbody> element sho uld alw ays come after a <thead> element a nd may come before or after a <tfoot> element.

<tr> HTML Tag

  • <tr align=””>
  • <tr valign=””>
  • <tr bgcolor=””>
  • <tr background=””>
  • <tr bordercolor=””>

The < tr> element is used to group tog ethe r &l t;th > or <td> values into a single row of table heading or dat a values. The <tr> element may be a d irect child of a <table> elem ent or ne sted wi thin a paren t <thead>, <tfoot>, or <tbody> element.

<thead> HTML Tag

The <capti on> element is used to add a caption to an HTML tab le. A < ;caption> must appear in an HTML document as the first descendant of a pa rent <table>, but it may be positioned visually at the bottom of the table with CSS.

The <c ol> element, typically implemented as a child element of a p arent < colgroup>, can be used to target a column in an HTML table.

The <colgro up> element is used a parent container for one or more <col>elements which are used to target columns in an HTML table.

Basic Styling

Distinguishing different parts of the table is easy if the table has different colors and lines. CSS table border is another common element. By default, all table cells are spaced out from one another by 2px. Between the first row and the rest, you will notice a slight extra gap caused by the default border-spacing being applied to the <the ad> ; and &l t;tbody> pushing them apart a bit extra.

You can control the spacing:

table {border-spacing: 0.5rem;}

Or you can simply remove that space:

table {border-collapse: collapse;}

HTML table padding, HTML table heading, borders, and making <th> elements left-aligned is a simple yet effective way to style your HTML tables.

Important Style Rules for Tables

CSS tables and their properties work great if you use them right. There are, however, some details to keep in mind. For example, if you apply a certain font-family to the table, but then a different one to the cell — the cell wins because it is the actual element with the text inside.

These properties are either unique to table elements or they behave uniquely on table elements.

vertical-align

Possible values : baseline, sub, super, text-top, text-bottom, middle, top, bottom, %, length

Aligns the content inside a cell. Works particularly well in tables, although only the top/bottom/middle make much sense in that context.

white-space

Possible values: normal, pre, nowrap, pre-wrap, pre-line

Controls how text wraps in a cell. Some data may need to be all on one line to make sense.

border-collapse

Possible values: collapse, separate

Applied to the table to determine if borders collapse into themselves (sort of like margin collapsing only bi-directional) or not. What if two borders that collapse into each other have conflicting styles (like color)? The styles applied to these types of elements will “win”, in order of “strength”: cell, row, row group, column, column group, table.

border-spacing

Possible values: length

If border-collapse is separate, you can specify how far cells should be spaced out from each other. The modern version of the cellspacing attribute. And speaking of that, padding is the modern version of the cellpadding attribute.

Width works on table cells just about how you would think it does, except when there is some kind of conflict.

For instance, if you tell the table itself to be 400px wide then the first cell of a three-cell row to be 100px wide and leave the others alone, that first cell will be 100px wide and the other two will split up the remaining space.

But if you tell all three of them to be 20000px wide, the table will still be 400px and it will just give each of them a third of the space. That’s assuming white-space or elements like an image don’t come into play.

Border works on any of the table elements and just about how you would expect. The quirks come in when you collapse the borders.

In this case, all table cells will have only one border width between them, rather than the two you would expect them to have (border-right on the first cell and border-left on the next cell).

In order to remove a border in a collapsed environment, both cells need to “agree” to remove it. Like this:

Otherwise, source order/specificity wins which border is shown on which edge.

table-layout

Possible values: auto, fixed

auto is the default. The width of the table and its cells depends on the content inside.

If you change this to fixed, the table and column widths are set by the widths of table and col elements or by the width of the first row of cells.

Cells in subsequent rows do not affect column widths, which can speed up rendering. If the content in subsequent cells can’t fit, the overflow property determines what happens.

Table Border

Table border CSS makes it easier to see the table and it is also the best method for displaying borders. Add styles, within the <style></style> tags located in the head element, to show the border for the table, th and td elements within your HTML document.

Connecting Cells

To understand how connected cells work, we need to explain the two attributes that can go on any table cell element: HTML rowspan and HTML colspan. If a td has a colspan of 2 (i.e. <td colspan=”2″>) will take up the space of two cells in a row horizontally even though it would still be a single cell. The same goes for rowspan, but vertically.

Rowspan is a bit harder to grasp simply because columns are grouped differently than rows. For example, with colspan, you get the final value by simply adding up the values for each table cell in the row. With rowspan, on the other hand, the row below it gets +1 to its table cell count and needs one less table cell to complete the row.

Nesting Tables

“Nesting tables” simply means placing a table inside another table which is doable, but you need to include the complete structure with the <table> element. However, it might not be the best idea because of the confusing markup and worse accessibility.

However, there are situations when this is absolutely necessary and yes, it is doable. So, for example, if you need to import content from other sources, you can import a table and place it inside your table.

Zebra Striping Tables

Colors are very helpful for the users to easily spot what they are looking for in the table. You can either set a background color to the table cell elements or you can set them on the table rows themselves.

This is the most basic example:

tbody tr:nth-child(odd) {background: #eee; }

Using tbody is useful if you don’t want to stripe header and footer rows. If you don’t want to let what is underneath show through, you can set the even rows as well.

If you need to support browsers that don’t understand: nth-child() (pretty damn old) you could use jQuery to do it.

Highlighting Rows and Columns

Highlighting rows is pretty easy; all it takes is adding a class name to a row.

Highlighting columns, on the other hand, takes a bit more effort. You can use the <c ol> element, which will allow you to set styles for cells that appear in the selected column. For example, a table with 4 columns in each row would need to h ave 4 <col> elements.

How to center an HTML Table

How to center a table in HTML? This question is pretty common among people designing their first HTML tables. The thing is that text-align:center doesn’t center a table as a whole — it just centers the text inside the cells.

Centering the whole table needs left and right margins set to auto , and top and bottom margins set to the values you need.

Say you want the top and bottom margins of your table to be one blank line (1em). The CSS code in the <tab le> tag is simply:

<table style=”margin:1em auto ;”>

If you wish to wrap text next to a table, use float:left to float the table to the left of the subsequent text. To put a little space between the table and the text, you can also put the right margin on the table, like this:

<table style=”float:left; margin-right:10px ;”>

If you want the table to be to the right of the neighboring text, use float:right instead. You can also set the left margin:

<table style=”float:right; margin-left:10px ;”>

Something to keep in mind: Make sure you put the text that should be next to the table after the closing </table> tag for the table. Floats float next to subsequent content in the code, not content that precedes the float.

1*IlTpsqI9LEC4vNclDhbuNQ

Can I nest tables within tables?

Yes, you can place an existing table inside the cell of another table. There is an example mentioned earlier in this article.

Keep in mind that the older browsers have problems with nested tables if you don’t explicitly close your TR , TD , and TH elements. To avoid these issues, include every </ tr >, </ td> ;, and </th> tag, even though the HTML specifications don’t require them.

Also, try not to nest tables more than a few rows deep into the table because the older browser versions often have problems with that. You can use the ROWSPAN and COLSPAN attributes to minimize table nesting.

Finally, be especially sure to validate your markup whenever you use nested tables.

How can I use tables to structure forms?

Within a TD element within a table, there can be small forms placed if you want to position a form relative to the other content. However, if you want to position the form-related elements relative to each other, it doesn’t really help.

If you want to do that, the entire table must be within the form. You can’t start a form in one TH or TD element and end in another. You can’t place the form within the table without placing it inside a TH or TD element. You can put the table inside the form, and then use the table to position the INPUT , TEXTAREA , SELECT , and other form-related elements, as shown in the following example.

Can I use percentage values for <TD WIDTH=…>?

The HTML 3.2 and HTML 4.0 specifications allow only integer values (representing a number of pixels) for the WIDTH attribute of the TD element. The he HTML 4.0 DTD, on the other hand, allows non-integer values (such as percentages), so an HTML validator will not complain about <TD WIDTH=”xx%”>.

Keep in mind that Netscape and Microsoft’s browsers interpret percentage values for <TD WIDTH=…> differently. On the other hand, their interpretations (and those of other table-aware browsers) match when combined with <TABLE WIDTH=”100%”>. In cases like that, percentage values can be used safely, even though they are prohibited by the public specifications.

Why doesn’t <TABLE WIDTH=”100%”> use the full browser width?

The margin between the content and the edge of the display area is quite narrow with graphical browsers. Navigator always leaves room for a scrollbar on the right. However, when the document is not long enough to require scrolling, the scrollbar doesn’t appear and this leaves you with the margin on the right that can’t be removed.

Why is there extra space before or after my table?

An invalid HTML syntax can cause extra space before and after HTML tables. The most common cause is the loose content within the table (i.e., content that is not inside a TD or TH element).

When it comes to the loose content, there isn’t a standard way to handle it. Some browsers display it before or after the table. When the loose content contains only multiple line breaks or empty paragraphs, all this empty space will be displayed before or after the table itself.

The solution is to fix the HTML syntax errors. All content within a table must be within a TD or TH element.

Are there any problems with using tables for layout?

The short answer would be — yes .

In order for the browsers to display the table, the HTML table attributes, particularly the HEIGHT or WIDTH attributes need to be known. The thing is that the entire table has to be downloaded with the known dimensions before being rendered. If the above-mentioned attributes aren’t known, the rendering process can be delayed.

In addition to that, if any of the table’s content is too wide for the available display area, the table has to stretch to display the oversized content. The rest of the content then adjusts to fit the oversized table rather than fitting the available display area. As a result of that, the users need to scroll horizontally to be able to read the content. The printed versions can also end up being cropped.

If the content is viewed on a display narrower than anticipated, the fixed-width tables cause the same problems as other oversized tables. If the displays are wider than anticipated, much of the display is will be wasted with the extremely wide margins. If the readers require larger fonts, the content will be displayed with only a few words per line.

One of the most important things to keep in mind is the correct syntax. The browsers don’t do well with invalid syntax. Nested tables may not display correctly with correct syntax either in older versions of Netscape Navigator.

Then there are also some browsers that completely ignore tables which means they would also ignore the layout created with the HTML tables. In addition to that, search engines also ignore them. What you normally see in search results is usually the text at the beginning of a document. As a result of that, if a table is used for layout, instead of the actual content, navigation links appear in the search.

Some versions of Navigator have problems linking to named anchors when they are inside a table that uses the ALIGN attribute. They associate the named anchor with the top of the table, instead of the content of the anchor. If you don’t use ALIGN attribute on your tables, this problem can be entirely avoided.

All that being said, if you insist on using HTML tables for layout, careful markup can help you minimize the related issues. Avoid placing wide content inside tables such as wide images, PRE elements with long lines, long URLs, and similar.

Use several independent tables rather than a single full-page layout. For instance, you could use a table to lay out a navigation bar at the top or the bottom of the page, and leave the main content completely outside any layout tables.

How to add a caption to your table with <caption>?

You add a caption to your table by putting it inside a <capti on> element and nesting it insid e the & lt;table> element. You should put it just below the ope ning <table> tag.

The purpose of the caption is to contain a description of the table content. This gives the readers a quick idea of whether the table contains the content they are searching for. However, it is particularly useful for the visually-impaired users who can avoid having the screen reader read a lot of the table content before realizing what the table is about.

A caption is placed directly beneath the <tab le> tag.

Note: The summary attribute can also be used on the <tab le> element to provide a description — this is also read out by screen readers. We’d recommend usin g the < ;caption> element instead because the summary is deprecated by the HTML5 table spec, and doesn’t appear on the page.

Best HTML Table Generator Tools

If you don’t want to deal with a bunch of HTML table code, using a good table generator tool could be really useful. Creating a table in HTML with a tool like this requires no knowledge of developing languages and it is pretty fast and simple.

In addition to that, the majority of the best tools of this sort are completely free of charge and everyone can use them. Basically, all you have to do is import the data, and customize the table (for example, HTML table border style, HTML table formatting, CSS table width, CSS table background color, cellspacing, cellpadding etc).

Once you are done with that, the generator will give you your table HTML code that you will simply copy and paste to your website. Easy-peasy.

Why Should You Use HTML Table Generator Tools

Designing a table from scratch is no easy task. Making it perfectly functional is an uphill battle and it takes a lot of time and effort — not to mention that the results often end up being less than perfect.

Instead of writing lines and lines of code with your notepad, you can save yourself a lot of time and trouble with the right HTML table generator tool. Not only is it easier but the results are often better than when you try to build the whole thing yourself. Not to mention how much time it will save you, and we all know time is money.

Tables generator

1*_EHfuyYjdmcl3NN4BkAcJQ

Very useful HTML table generator tool. Easy to use and it allows you to choose the theme you like best. You can learn more about it on the official website.

1*GD-6r6smQraAI_El5jk58g

A simple and easy-to-use tool that also happens to be free of charge.

1*C4G_v1UPRcQCsY60avTwAg

Truben allows you to make all kinds of HTML tables quickly and easily.

Html-tables

1*xk9W4CUlPP3aXKWwCz-Zwg

A handy tool that works similarly to word processors. It lets you create beautiful tables free of charge.

CSS Table generator

1*bwDVOj6xgPOOhsgeDdLHjA

Great tool for creating stylish tables without the use of images.

Tablestyler

1*Ke1T1TXqDO-0w67w2E4w6A

Use table CSS elements and create gorgeous HTML tables with this online tool.

1*FBGbuZ-IHehw5esqSTKSwQ

A simple tool for creating your favorite table style.

1*BYzMYV3bC9hwhTvwfsZsvA

One of the simplest tools; perfect for people with little technical knowledge and/or slow internet connection.

RapidTables

1*u0Iqq-tKoNWD9cow5kOrLg

This tool comes with a variety of generating options and creating great HTML tables is one of them.

1*Zwb6_Tv214beAfvZs_vtIA

A useful generator for designing HTML tables out of spreadsheet data.

Ending thoughts on learning about HTML Tables

Creating beautiful and functional HTML tables is no easy task. If you want to build them from scratch, you have to have a certain amount of coding knowledge and developing experience because there are many things to consider if you want the table display the content properly.

If, on the other hand, you are looking for a quick solution that requires no coding experience, you could always consider using one of many handy table generator tools. Not only will they save you a lot of time and trouble, but the results will also be amazing.

If you enjoyed reading this article about HTML tables, you should also read these:

  • CSS tables and their code that you can use
  • Building Responsive Tables with CSS & HTML or WordPress
  • jQuery Table Plugins You Should Check Out

Originally published at wpdatatables.com on October 31, 2018.

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Table Of Content

Tables are used to group informations in various rows and columns together. The basic table looks like this::

It looks so complex, Is not it ? <table> tag has 3 childs : thead, tbody and tfoot , where tfoot is rarely used so in practice, we use only thead and tbody . So now it looks something like this ::

As thead represents the header of the table, it will wrap only one row (tr) inside it. And again this tr will wrap as many th as it needs column header. th means header cells and it exists in thead. In terms of code, kindly have a look below::

tbody represents the body of the table, it will wrap as many rows as it needs (tr) inside it. And again this tr will wrap as many td as it needs column headers data. td means data cells and it exists in tbody. In terms of code, kindly have a look below::

  • border attribute and border-collapse styling to collapse double borders is the firsr and very important concept in html table.
  • colspan attribute : If this attribute is used on a th or td cells then those cells will merge those columns as one column. e.g : colspan = "4" will merge 4 cells(th/td) into one cell. And this property always used on th/td only.
  • rowspan attribute : If this attribute is used on a th or td cells then those cells will merge those rows as one row. e.g : rowspan = "4" will merge 4 cells(th/td) into one cell. And this property always used on td only.
  • cellpadding attribute : This attribute is applied on a table tag and it will give padding to all the th/th cells.
  • cellspacing attribute : This attribute is applied on a table tag and it will give spaces/margin between different cells.

Example of border attribute and border-collapse styling

Now focus that on table tag, we have border="1" , meaning border of table is set to 1px, and then you see a double border. Once you apply a styling of border-collapse: collapse then double borders are collapsed. Note : Here we are using html style attribute to do styling, but in practice we write this style in a css file. I am attaching 2 images here , one for double border and then collapse of double borders, which is what we want.

table borders

Example of colspan and rowspan attribute

We can use colspan and rowspan attribute separately also, based on businedd requirement or figma design. But here i will show you both used together and explain you in detail.

table colspan and rowspan

As it is very simple to understand, here in the 3rd row(tr), we have only one td, but in thead, the maximum columns we have is 3, so we are trying to merge 3 columns cells into one with colspan = "3" attribute. Now as for rowspan usage, in the first row in tbody the attribute rowspan = "2" , will merge 2 row cells into one:: row 1 cell 1 and row 2 cell 1 are merged into one cell row 1 cell 1.

Mastering the Table Tag in HTML: A Comprehensive Guide

Faraz Logo

By Faraz - August 14, 2023

Learn how to effectively use the table tag in HTML to structure and organize your web content. Discover the power of this versatile HTML element for better design and user experience.

Mastering the Table Tag in HTML A Comprehensive Guide.jpg

If you're delving into the world of web development, understanding the <table> tag in HTML is a fundamental skill that can greatly enhance your ability to structure and organize data on your web pages. In this guide, we will take you through the ins and outs of mastering the <table> tag, empowering you to create visually appealing and well-organized content.

Table of Contents

  • What is the Table Tag in HTML?
  • The Anatomy of a Table
  • Adding Headers to Your Table
  • Adding a Footer Row
  • Spanning Rows and Columns
  • Adding the Caption to Your Table
  • Formatting and Styling Tables
  • Responsive Tables
  • Best Practices for Using Tables
  • Best Practices for SEO
  • Frequently Asked Questions (FAQs)

1. What is the Table Tag in HTML?

The table tag is at the heart of HTML's table structure. It consists of several sub-elements that work together to create a comprehensive table layout. Let's break down the essential components:

  • <table> : This is the main container for the entire table. It holds all the rows and columns within.
  • <thead> : This element contains the table's header content, typically including column headings.
  • <tbody> : The table body contains the main content, organized into rows and columns.
  • <tr> : Stands for "table row." It defines a row within the table.
  • <th> : Represents a table header cell. It's used to define column or row headers.
  • <td> : Denotes a regular table cell that holds data.

2. The Anatomy of a Table

Before we delve deeper, let's break down the basic structure of a table:

In this example, <table> marks the beginning of the table, <tr> represents a row, <th> is used for header cells, and <td> denotes data cells. This hierarchical structure forms the basis of a table layout.

3. Adding Headers to Your Table

Headers provide context and meaning to the data presented within a table. By using the <thead> (table head) and <tbody> (table body) tags, you can separate header content from the main data. This separation enhances accessibility and allows for better styling options.

4. Adding a Footer Row

To create a footer for your table, you can use the <tfoot> (table footer) element. Just as the <thead> (table head) separates header content, the <tfoot> element segregates footer content from the main body of the table. Inside the <tfoot> element, you can include one or more rows using the <tr> (table row) tag, and within those rows, use the <td> (table data) or <th> (table header) tags to define the cells.

5. Spanning Rows and Columns

Sometimes, you may need a cell to span multiple rows or columns. This can be achieved using the rowspan and colspan attributes. For instance:

6. Adding the Caption to Your Table

To add a caption to your HTML table, simply insert the <caption> element immediately after the opening <table> tag. Inside the <caption> element, you can provide concise and descriptive text that encapsulates the table's content. This text should be meaningful and informative, helping users quickly grasp the essence of the table.

7. Formatting and Styling Tables

CSS can greatly enhance the appearance of tables by controlling borders, spacing, colors, and more. You can target specific tables or elements within tables to apply styles. For instance:

These CSS rules will create a consistent border and padding for all cells in your table.

8. Responsive Tables

In the era of mobile devices, it's crucial to ensure your tables are responsive. You can achieve this by using media queries and adjusting the table layout to fit smaller screens. Here's an example:

9. Best Practices for Using Tables

To make the most of the <table> tag, consider these best practices:

  • Semantics Matter: Always use <th> for header cells and <td> for data cells. This not only improves accessibility but also helps search engines understand your content better.
  • Mindful of Responsiveness: In an era of diverse devices, ensure your tables are responsive. Use CSS techniques like media queries to adapt the table's layout for different screen sizes.
  • Limit Cell Content: Keep cell content concise. Long strings of text can disrupt the table's layout. Consider using tooltips for lengthy data.
  • Use CSS for Styling: While the <table> tag offers basic styling options, leverage CSS to achieve a polished and consistent design. Apply colors, borders, and spacing through CSS rules.

10. Best Practices for SEO

To ensure your tables contribute positively to SEO, consider the following tips:

  • Semantic Structure: Use appropriate header tags ( <th> ) and data cells ( <td> ) for better SEO and accessibility.
  • Descriptive Labels: Provide meaningful and descriptive headers to help search engines understand your table content.
  • Concise Content: Keep your table content concise and relevant, avoiding excessive use of cells or rows.
  • Mobile-Friendly: Implement responsive design to make your tables look and work well on various screen sizes.

11. Conclusion

Mastering the <table> tag in HTML opens doors to dynamic and visually appealing data presentation on your web pages. By adhering to best practices and employing CSS for styling, you can create tables that are both informative and aesthetically pleasing. Remember, the key lies in striking the balance between function and design to deliver an exceptional user experience.

To sum up, the <table> tag is a cornerstone of web development that empowers you to organize, structure, and present data effectively. With its versatile features and compatibility across browsers, the <table> tag is an invaluable asset in your coding toolkit. As you continue your journey in web development, make sure to embrace the power of the <table> tag and unlock new dimensions of content presentation.

12. Frequently Asked Questions (FAQs)

1. why should i use html tables instead of other layout options.

HTML tables are best suited for displaying tabular data. If your content requires structured organization, tables provide an efficient solution.

2. Can I apply different styles to individual cells within a table?

Yes, you can apply unique styles to specific cells using CSS classes or inline styles.

3. Do tables affect my website's SEO?

When used appropriately, tables can enhance SEO by providing well-structured content. However, overusing tables for layout can have negative implications.

4. Are there any JavaScript libraries to make tables interactive?

Yes, DataTables is a popular library for creating feature-rich and interactive tables.

5. How do I ensure my tables are accessible to all users?

Use semantic markup, provide alternative text, and implement ARIA attributes to ensure accessibility for users with disabilities.

create a tailwind login page responsive design.jpg

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks! Faraz 😊

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox, latest post.

Crafting an Engaging Pet Food Shop Template: HTML, CSS, JavaScript

Crafting an Engaging Pet Food Shop Template: HTML, CSS, JavaScript

Discover how to create a visually stunning pet food shop template using HTML, CSS, and JavaScript. Elevate your online presence and attract more customers today!

How to Create a Scrollable Sticky Sidebar with HTML, CSS, and JavaScript

How to Create a Scrollable Sticky Sidebar with HTML, CSS, and JavaScript

May 18, 2024

Creating a Shopping Cart Concept Using HTML, CSS, Vue, and Slick.js

Creating a Shopping Cart Concept Using HTML, CSS, Vue, and Slick.js

Creating a Responsive Bootstrap Dashboard: Source Code Included

Creating a Responsive Bootstrap Dashboard: Source Code Included

May 14, 2024

Create Your Own Bubble Shooter Game with HTML and JavaScript

Create Your Own Bubble Shooter Game with HTML and JavaScript

May 01, 2024

How to Create a Scroll Down Button: HTML, CSS, JavaScript Tutorial

How to Create a Scroll Down Button: HTML, CSS, JavaScript Tutorial

Learn to add a sleek scroll down button to your website using HTML, CSS, and JavaScript. Step-by-step guide with code examples.

How to Create a Trending Animated Button Using HTML and CSS

How to Create a Trending Animated Button Using HTML and CSS

March 15, 2024

Create Interactive Booking Button with mask-image using HTML and CSS (Source Code)

Create Interactive Booking Button with mask-image using HTML and CSS (Source Code)

March 10, 2024

Create Shimmering Effect Button: HTML & CSS Tutorial (Source Code)

Create Shimmering Effect Button: HTML & CSS Tutorial (Source Code)

March 07, 2024

How to Create a Liquid Button with HTML, CSS, and JavaScript (Source Code)

How to Create a Liquid Button with HTML, CSS, and JavaScript (Source Code)

March 01, 2024

Learn how to develop a bubble shooter game using HTML and JavaScript with our easy-to-follow tutorial. Perfect for beginners in game development.

Build a Number Guessing Game using HTML, CSS, and JavaScript | Source Code

Build a Number Guessing Game using HTML, CSS, and JavaScript | Source Code

April 01, 2024

Building a Fruit Slicer Game with HTML, CSS, and JavaScript (Source Code)

Building a Fruit Slicer Game with HTML, CSS, and JavaScript (Source Code)

December 25, 2023

Create Connect Four Game Using HTML, CSS, and JavaScript (Source Code)

Create Connect Four Game Using HTML, CSS, and JavaScript (Source Code)

December 07, 2023

Creating a Candy Crush Clone: HTML, CSS, and JavaScript Tutorial (Source Code)

Creating a Candy Crush Clone: HTML, CSS, and JavaScript Tutorial (Source Code)

November 17, 2023

Create Image Color Extractor Tool using HTML, CSS, JavaScript, and Vibrant.js

Create Image Color Extractor Tool using HTML, CSS, JavaScript, and Vibrant.js

Master the art of color picking with Vibrant.js. This tutorial guides you through building a custom color extractor tool using HTML, CSS, and JavaScript.

Build a Responsive Screen Distance Measure with HTML, CSS, and JavaScript

Build a Responsive Screen Distance Measure with HTML, CSS, and JavaScript

January 04, 2024

Crafting Custom Alarm and Clock Interfaces using HTML, CSS, and JavaScript

Crafting Custom Alarm and Clock Interfaces using HTML, CSS, and JavaScript

November 30, 2023

Detect User's Browser, Screen Resolution, OS, and More with JavaScript using UAParser.js Library

Detect User's Browser, Screen Resolution, OS, and More with JavaScript using UAParser.js Library

October 30, 2023

URL Keeper with HTML, CSS, and JavaScript (Source Code)

URL Keeper with HTML, CSS, and JavaScript (Source Code)

October 26, 2023

Creating a Responsive Footer with Tailwind CSS (Source Code)

Creating a Responsive Footer with Tailwind CSS (Source Code)

Learn how to design a modern footer for your website using Tailwind CSS with our detailed tutorial. Perfect for beginners in web development.

Crafting a Responsive HTML and CSS Footer (Source Code)

Crafting a Responsive HTML and CSS Footer (Source Code)

November 11, 2023

Create an Animated Footer with HTML and CSS (Source Code)

Create an Animated Footer with HTML and CSS (Source Code)

October 17, 2023

Bootstrap Footer Template for Every Website Style

Bootstrap Footer Template for Every Website Style

March 08, 2023

How to Create a Responsive Footer for Your Website with Bootstrap 5

How to Create a Responsive Footer for Your Website with Bootstrap 5

August 19, 2022

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

HTML table advanced features and accessibility

  • Overview: HTML tables

In the second article in this module, we look at some more advanced features of HTML tables — such as captions/summaries and grouping your rows into table head, body and footer sections — as well as looking at the accessibility of tables for visually impaired users.

Adding a caption to your table with <caption>

You can give your table a caption by putting it inside a <caption> element and nesting that inside the <table> element. You should put it just below the opening <table> tag.

As you can infer from the brief example above, the caption is meant to contain a description of the table contents. This is useful for all readers wishing to get a quick idea of whether the table is useful to them as they scan the page, but particularly for blind users. Rather than have a screen reader read out the contents of many cells just to find out what the table is about, the user can rely on a caption and then decide whether or not to read the table in greater detail.

A caption is placed directly beneath the <table> tag.

Note: The summary attribute can also be used on the <table> element to provide a description — this is also read out by screen readers. We'd recommend using the <caption> element instead, however, as summary is deprecated and can't be read by sighted users (it doesn't appear on the page).

Active learning: Adding a caption

Let's try this out, revisiting an example we first met in the previous article.

  • Open up your language teacher's school timetable from the end of HTML Table Basics , or make a local copy of our timetable-fixed.html file.
  • Add a suitable caption for the table.
  • Save your code and open it in a browser to see what it looks like.

Note: You can find our version on GitHub — see timetable-caption.html ( see it live also ).

Adding structure with <thead>, <tbody>, and <tfoot>

As your tables get a bit more complex in structure, it is useful to give them more structural definition. One clear way to do this is by using <thead> , <tbody> , and <tfoot> , which allow you to mark up a header, body, and footer section for the table.

These elements don't make the table any more accessible to screen reader users, and don't result in any visual enhancement on their own. They are however very useful for styling and layout — acting as useful hooks for adding CSS to your table. To give you some interesting examples, in the case of a long table you could make the table header and footer repeat on every printed page, and you could make the table body display on a single page and have the contents available by scrolling up and down.

To use them, they should be included in the following order:

  • The <thead> element must wrap the part of the table that is the header — this is usually the first row containing the column headings, but this is not necessarily always the case. If you are using <col> / <colgroup> elements, the table header should come just below those.
  • The <tbody> element needs to wrap the main part of the table content that isn't the table header or footer.
  • The <tfoot> element needs to wrap the part of the table that is the footer — this might be a final row with items in the previous rows summed, for example.

Note: <tbody> is always included in every table, implicitly if you don't specify it in your code. To check this, open up one of your previous examples that doesn't include <tbody> and look at the HTML code in your browser developer tools — you will see that the browser has added this tag for you. You might wonder why you ought to bother including it at all — you should, because it gives you more control over your table structure and styling.

Active learning: Adding table structure

Let's put these new elements into action.

  • First of all, make a local copy of spending-record.html and minimal-table.css in a new folder.
  • Try opening it in a browser — You'll see that it looks OK, but it could stand to be improved. The "SUM" row that contains a summation of the spent amounts seems to be in the wrong place, and there are some details missing from the code.
  • Put the obvious headers row inside a <thead> element, the "SUM" row inside a <tfoot> element, and the rest of the content inside a <tbody> element.
  • Save and refresh, and you'll see that adding the <tfoot> element has caused the "SUM" row to go down to the bottom of the table.
  • Next, add a colspan attribute to make the "SUM" cell span across the first four columns, so the actual number appears at the bottom of the "Cost" column.
  • Let's add some simple extra styling to the table, to give you an idea of how useful these elements are for applying CSS. Inside the head of your HTML document, you'll see an empty <style> element. Inside this element, add the following lines of CSS code: css tbody { font-size : 95% ; font-style : italic ; } tfoot { font-weight : bold ; }
  • Save and refresh, and have a look at the result. If the <tbody> and <tfoot> elements weren't in place, you'd have to write much more complicated selectors/rules to apply the same styling.

Note: We don't expect you to fully understand the CSS right now. You'll learn more about this when you go through our CSS modules ( Introduction to CSS is a good place to start; we also have an article specifically on styling tables ).

Your finished table should look something like the following:

Note: You can also find it on GitHub as spending-record-finished.html .

Nesting Tables

It is possible to nest a table inside another one, as long as you include the complete structure, including the <table> element. This is generally not really advised, as it makes the markup more confusing and less accessible to screen reader users, and in many cases you might as well just insert extra cells/rows/columns into the existing table. It is however sometimes necessary, for example if you want to import content easily from other sources.

The following markup shows a simple nested table:

The output of which looks something like this:

Tables for visually impaired users

Let's recap briefly on how we use data tables. A table can be a handy tool, for giving us quick access to data and allowing us to look up different values. For example, it takes only a short glance at the table below to find out how many rings were sold in Gent during August 2016. To understand its information we make visual associations between the data in this table and its column and/or row headers.

But what if you cannot make those visual associations? How then can you read a table like the above? Visually impaired people often use a screen reader that reads out information on web pages to them. This is no problem when you're reading plain text but interpreting a table can be quite a challenge for a blind person. Nevertheless, with the proper markup we can replace visual associations by programmatic ones.

Note: There are around 253 Million people living with Visual Impairment according to WHO data in 2017 .

This section of the article provides further techniques for making tables as accessible as possible.

Using column and row headers

Screen readers will identify all headers and use them to make programmatic associations between those headers and the cells they relate to. The combination of column and row headers will identify and interpret the data in each cell so that screen reader users can interpret the table similarly to how a sighted user does.

We already covered headers in our previous article — see Adding headers with <th> elements .

The scope attribute

A new topic for this article is the scope attribute, which can be added to the <th> element to tell screen readers exactly what cells the header is a header for — is it a header for the row it is in, or the column, for example? Looking back to our spending record example from earlier on, you could unambiguously define the column headers as column headers like this:

And each row could have a header defined like this (if we added row headers as well as column headers):

Screen readers will recognize markup structured like this, and allow their users to read out the entire column or row at once, for example.

scope has two more possible values — colgroup and rowgroup . These are used for headings that sit over the top of multiple columns or rows. If you look back at the "Items Sold August 2016" table at the start of this section of the article, you'll see that the "Clothes" cell sits above the "Trousers", "Skirts", and "Dresses" cells. All of these cells should be marked up as headers ( <th> ), but "Clothes" is a heading that sits over the top and defines the other three subheadings. "Clothes" therefore should get an attribute of scope="colgroup" , whereas the others would get an attribute of scope="col" :

The same applies to headers for multiple grouped rows. Take another look at the "Items Sold August 2016" table, this time focusing on the rows with the "Amsterdam" and "Utrecht" headers ( <th> ). You'll notice that the "The Netherlands" header, also marked up as a <th> element, spans both rows, being the heading for the other two subheadings. Therefore, scope="rowgroup" should be specified on this header cell to help screen readers create the correct associations:

The id and headers attributes

An alternative to using the scope attribute is to use id and headers attributes to create associations between headers and cells.

The headers attribute takes a list of unordered, space-separated strings , each corresponding to the unique id of the <th> elements that provide headings for either a data cell ( <td> element) or another header cell ( <th> element).

This gives your HTML table an explicit definition of the position of each cell in the table, defined by the header(s) for each column and row it is part of, kind of like a spreadsheet. For it to work well, the table really needs both column and row headers.

Returning to our "Items Sold August 2016" example, we can use the id and headers attributes as follows:

  • Add a unique id to each <th> element in the table.
  • Add a headers attribute to each <th> element that acts as a subheading, i.e., has a header element above it. The value is the id of the heading that sits over the top and defines the subheadings, which is "clothes" for the column headers and "belgium" for the row header in our example.
  • Add a headers attribute to each <td> element and add the id s of the associated <th> element(s) in form of a space-separated list. You can proceed as you would in a spreadsheet: Find the data cell and search for the corresponding headings for the row and column. The order of the specified id s doesn't matter, but you should be consistent to keep it organized.

Note: This method creates very precise associations between headers and data cells but it uses a lot more markup and does not leave any room for errors. The scope approach is usually sufficient for most tables.

Active learning: playing with scope and headers

  • For this final exercise, we'd like you to first make local copies of items-sold.html and minimal-table.css , in a new directory.
  • Now try adding in the appropriate scope attributes to make this table more accessible.
  • Finally, try making another copy of the starter files, and this time make the table more accessible by creating precise and explicit associations using id and headers attributes.

Note: You can check your work against our finished examples — see items-sold-scope.html ( also see this live ) and items-sold-headers.html ( see this live too ).

There are a few other things you could learn about tables in HTML, but this is all you need to know for now. Next, you can test yourself with our HTML tables assessment . Have fun!

If you are already learning CSS and have done well on the assessment, you can move on and learn about styling HTML tables — see Styling tables .

If you want to get started with learning CSS, check out the CSS Learning Area !

  • HTML Tutorial
  • HTML Exercises
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • DOM Audio/Video
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter

How to Create Table in HTML?

  • How to group the body content in a table using HTML5 ?
  • How create table without using <table> tag ?
  • What is the rule attribute in HTML Table ?
  • Why should we avoid use of tables for layout in HTML ?
  • How to fix the height of rows in the table?
  • How to set the number of rows a table cell should span in HTML ?
  • How to set fixed width for <td> in a table ?
  • How to merge table cells in HTML ?
  • How to Create Time-Table Schedule using HTML ?
  • How to Create Nested tables within tables in HTML ?
  • How to use tables to structure forms ?
  • How to fix the width of columns in the table ?
  • How to center contents of an HTML table ?
  • How to fetch data from JSON file and display in HTML table using jQuery ?
  • How to perform a real time search and filter on a HTML table?
  • How to use header & footer in HTML table ?
  • How to apply border inside a table ?
  • What are Cell Padding & Cell Spacing in HTML Table ?
  • HTML Table Padding and Spacing
  • How to create table with 100% width, with vertical scroll inside table body in HTML ?
  • How to Reduce Space Between Two Columns in HTML Table ?
  • Can I Add Multiple <tbody> Elements in Same Table in HTML ?
  • How to add table footer in HTML ?
  • What are the HTML tags used to display the data in the tabular form ?
  • How to add tooltip to HTML table cell without using JavaScript ?

HTML tables are essential for organizing and displaying data in a structured format on web pages. Creating a table in HTML is a fundamental skill for web developers. It is used for product information, presenting data analytics, or designing a pricing comparison chart, etc. This article provides a step-by-step guide on how to create tables in HTML.

Table of Content

Elements of HTML Table

Table structure, basic syntax of html table, adding table heading to rows, html table with thead, tbody, and tfoot elements.

Note: The <thead>, <tbody>, <tfoot> elements help to organize the table structure logically and are optional but recommended for clarity.

Within the <table> element, the table structure is organized as rows (<tr>) and columns defined by header cells (<th>) or data cells (<td>). Rows (<tr>) contain one or more cells (<th> or <td>), depending on the structure of the table.

Example: Here is an example of HTML table with two rows and three columns.

Note: The border attribute is not supported by HTML5. CSS border property is used to set the table border in HTML5.

html-table

To add a table heading to rows in an HTML table, you can use the <th> element within the <tr> element. This is useful when you have data that represents headings for each row.

html-table-with-heading

The <thead> section is used for headers that describe the columns of the table. The <tbody> section contains the main data rows. The <tfoot> section provides a footer row typically used for summary information or totals.

This structure follows best practices for organizing data in HTML tables and provides clear separation between the table header, body, and footer sections.

html-table-with-thead-tbody

Please Login to comment...

Similar reads.

  • HTML-Questions
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

CodingFusion

12 beautiful HTML table examples for beginners to practice

12 HTML table examples for beginners to practice. Using these examples beginner developers can practice HTML Table attributes, various CSS properties to enhance their HTML Table and CSS knowledge. These examples will help users to understand following scenerios:

1) HTML table Border. 2) HTML table Alternate Row background color. 3) HTML table Alternate Column background color. 4) HTML table Cellpading. 5) HTML table Cellspacing. 6) HTML table RowSpan. 7) HTML table ColSpan.

1) HTML Table Example-First

Write a program to create HTML table with the following output :

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

2) HTML Table Example-Second

Write a program to create HTML table using CSS having following output: 

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

3) HTML Table Example-Third

Write a program to create HTML table having cell borders using CSS to create following output:  

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

4) HTML Table Example-Fourth

Write a program to create HTML table having border and alternate row background colors using CSS.Final output should be like this:

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

5) HTML Table Example-Fifth

Write a program to create HTML table having border and alternate columns background colors using CSS. Final output should be like this: 

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

6) HTML Table Example-Sixth

Write a program to create HTML table and apply border to its single cell using CSS. Final output should be like this:

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

7) HTML Table Example-Seventh

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

8) HTML Table Example-Eighth

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

9) HTML Table Example-Ninth

Write a program to create HTML table with the following output : "Column having value Disclaimer is on top of the column"

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

10) HTML Table Example-Tenth

Write a program to create HTML table with the following output (make sure text have some space around them) :

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

11) HTML Table Example-Eleventh

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

12) HTML Table Example-Twelfth

12-HTML-Table-examples-for-beginners-to-practice-codingfusion

  • Popular Articles
  • Recent Articles

Subscribe for Latest Updates.

HTML Tutorial

Html graphics, html examples, html references, html exercises.

You can test your HTML skills with W3Schools' Exercises.

We have gathered a variety of HTML exercises (with answers) for each HTML Chapter.

Try to solve an exercise by editing some code. Get a "hint" if you're stuck, or show the answer to see what you've done wrong.

Count Your Score

You will get 1 point for each correct answer. Your score and total score will always be displayed.

Start HTML Exercises

Start HTML Exercises ❯

If you don't know HTML, we suggest that you read our HTML Tutorial from scratch.

Kickstart your career

Get certified by completing the course

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Tutorials Class - Logo

Basic HTML Page layout using table tag

A web page layout is often divided into multiple columns. Then these columns are treated as different sections of data. There are two most popular ways to create those columns in html page. One way is using <div>  tag and another way is using HTML  <table>  tag.

Most of the website layout has one common header area where we place website logo or tagline (sometimes menu as well). Then we have main content section divided into two or three columns. Bottom of the webpage contains a common footer section, where we can place logo, copyright statement, menu or some other content.

In two columns we have one left or right sidebar area and one content area. In three columns page design, we have left sidebar area, main content area and then one right sidebar area.

Creating a HTML page layout using table tags

Let us create a two column layout along with header and footer area using HTML table.

Share this post:

  • HTML Categories
  • HTML Page Layout Scripts Categories
  • HTML Form Codes Categories

Simply Coding

Web Designing

table tag assignment in html

HTML Tables Question Bank

  • Categories Web Designing , HTML , HTML

This post contains 1 mark questions on the topic of HTML Tables in the form of MCQs, fill in the blanks and true or false statements.

M ultiple choice questions:.

  • <thead>,<body>,<tr>
  • <table>,<head>,<tfoot>
  • <table>,<tr>,<td>
  • <table>,<tr>,<tt>
  • <caption>
  • <head>
  • <heading>
  • None of these
  • <row>
  • <colspan>
  • <rowspan>
  • <table>
  • bordercolor
  • border color
  • cellpadding
  • src and height
  • height and width
  • border and src
  • they do not have any common attributes
  • Table Definition
  • Table Design
  • <td valign = “left”>
  • <td align = “left”>
  • <td left align>
  • <td left>
  • <td align = “right”>
  • <td valign = “right”>
  • <td right=”align”>
  • None of the above
  • Both (a) and (b)
  • cellspacing
  • <TD>        
  • <TROW>
  • <TR>       
  • <ROW>
  • <TR>              
  • <TD>            
  • <TH>         
  • <TABLE>
  • <table>            
  • <caption>             
  • <td>    

State whether the following statements are true or false:

  • A cell is an intersection of a row and a column.
  • The cellpadding attribute is used with <td> tag.

Ans.  False 

  • <caption> is placed just above the <table> tag.

Ans.  False

  • <td> will make the text bold.
  • The border is an attribute of <a> tag.
  • The default value of border attribute is 1.
  • The cols value in the rules attribute, allows you to display table border only between columns.

Ans.  True 

  • The cellspacing attribute tells the browser how much space to include between the walls of the table.
  • <caption> tag gives heading to a Web page.
  • cellpadding attribute is used with <body> tag.
  • The rowspan attribute with < table > tag is used to merge more than one cells row wise.
  • The rowspan attribute is used to make a cell span multiple columns.
  • The align and valign are the attributes used with <td> tag to set the alignment of data in a cell.
  • The <td> tag (column setting) have higher priority than <tr> tag (row setting).
  • Table row <tr> tag can accept one attribute.
  • <th>‘tag is used to specify the column heading in a table.
  • ROWSPAN attribute with <table > tag is used merge more than one cell row wise
  • Align and valign are the attributes used with <TD> tag to set the alignment of data in a table.
  • <TR> tag is used to specify the individual row in a table

Fill in the blanks:

  • To insert a table on a Web page, we use  __________ tag.

Ans. <table>

  • The tag to start a table is __________
  • _________ tag is used to insert data into a table.

Ans <td>

  • The __________ attribute is used to display a specific portion of a table border.
  • frame attribute is used with _________ attribute.

Ans. border

  • In the rules attribute, the ________ value helps to display a table border only between rows.
  • Cellspacing is used to create space between different _________ in a table.
  • The _________ is an attribute of the < table > tag to set the distance between the cell content and its boundary.

Ans. cellpadding

  • To set image as background of an HTML table, you can use __________ attribute.

Ans. background

  • By default, color of a table is __________
  • The height and width attributes of < table > tag are specified in terms of _________ or percentage.

Ans. pixels

  • <td> tag can only be present inside _________

Ans. <tr>

  • The _________ attributes is used to combine the cells vertically.

Ans. rowspan

  • The __________ attribute is used to span two or more columns in a table.

Ans. colspan

  • The __________ attribute is used to align the data vertically within cells.

Ans. valign

  • The <tr> tag can only be present inside _________tag.
  • The <thead> tag is used to specify the _________ part of the table.
  • _________ altribute is used to span two or more column in a table
  • An _________ link allows a link to another section on the same web page

Ans. Internal

  • __________ is used to combine the cells vertically .      

Ans. Cellpadding

  • __________ is an attribute of the <table > tag to set the minimum distance between two adjacent cells     

Ans. Cellspacing 

  • __________ tag is used to create a table row.
  • The _________ tag is used to specify the individual table data in a table              

Ans. <TD>

  • IN HTML while creation a table, we can use HTML background altribute with __________ tag

Ans. <TR>

User Avatar

Previous post

HTML Formatting Tags Question Bank

Html image tag question bank, you may also like.

HTML Table tags

HTML Table Tags

HTML List

HTML List Tags

Audio and Video tag in HTML

HTML Audio and Video tags

Leave a reply cancel reply.

You must be logged in to post a comment.

Login with your site account

Remember Me

Not a member yet? Register now

Register a new account

I accept the Terms of Service

Are you a member? Login now

IMAGES

  1. How to Create Table using Table Tag in HTML : For Beginner

    table tag assignment in html

  2. #14: HTML Tag

    table tag assignment in html

  3. How to make table in HTML

    table tag assignment in html

  4. HTML Table Tags

    table tag assignment in html

  5. Basic Html Tags Table

    table tag assignment in html

  6. Table Tag In HTML

    table tag assignment in html

VIDEO

  1. List in HTML

  2. table tag with border tag archives in HTML, CSS and JavaScript frameworks etc in Cyber security 😈🐬

  3. table

  4. Table Tag Part 3 Colsoan & Rowspan in HTML URDU/HINDI

  5. Create table in website using table tag in html in hindi

  6. Table tag

COMMENTS

  1. HTML table tag

    W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

  2. HTML table basics

    HTML tables should be used for tabular data — this is what they are designed for. Unfortunately, a lot of people used to use HTML tables to lay out web pages, e.g. one row to contain the header, one row to contain the content columns, one row to contain the footer, etc. ... Tables produce tag soup: As mentioned above, table layouts generally ...

  3. : The Table element

    The examples below include tables of progressively increasing complexity. For additional examples, including an in-depth tutorial, see the HTML tables series in the Learn web development area, where you'll learn how to use the table elements and their attributes to correctly structure your tabular data. A Styling tables guide provides table styling information, including common, useful techniques.

  4. HTML Tables

    An HTML Table is an arrangement of data in rows and columns in tabular format. Tables are useful for various tasks, such as presenting text information and numerical data. A table is a useful tool for quickly and easily finding connections between different types of data. Tables are also used to create databases.

  5. HTML Tables

    In HTML, with the help of tables, you can arrange data like images, text, links and so on into rows and columns of cells. The use of tables in the web has become more popular recently because of the amazing HTML table tags that make it easier to create and design them. To create a table in HTML you will need to use tags. The most important one ...

  6. HTML <table> Tag: Usage, Attributes, and Practical Examples

    Explore the multifaceted world of HTML with our comprehensive guide on the tag. Learn about its usage, attributes and real-world examples that make coding tables easier and more efficient. Ideal for beginners and experienced coders alike in enhancing their web development skills.

  7. HTML Table (With Examples)

    HTML tables are useful for displaying data in a structured way. In this tutorial, you will learn how to create and use HTML table elements with examples. You will also learn how to apply different styles and attributes to your tables. This tutorial is suitable for beginners who want to learn the basics of HTML tables.

  8. Easy Tutorial For Creating HTML Tables That Add Value To Pages

    Adding Structure to a Table. There are additional elements we can use to add semantic meaning to the data in our table. The most important element, and one that should be present for every table, is the table heading th tag. This tag is used in place of the td tags in the first row to identify entries that should be used as column headings.. There are other elements which may optionally be ...

  9. A Comprehensive Guide to Tables in HTML5: Creating Structured Data

    HTML tables are a way to organize and display tabular data on a webpage. A table consists of rows and columns, forming a grid-like structure. Each cell within the table can contain data or other HTML elements. Tables provide a structured format for presenting data in a clear and organized manner.

  10. HTML Tables: All there is to know about them

    An HTML table is a great way to display things such as financial data, calendars, pricing, feature comparison, the nutrition facts information panel, bowling scores, and many other tabular data. There is a chance you have heard that the tables were unsemantic. However, that is not at all true.

  11. Working with HTML Tables: Practical Usage and Best Practices

    Master the creation and styling of HTML tables with our comprehensive tutorial. Learn how to structure tabular data using the "table", "tr", and "td" tags. Explore various attributes and techniques for adding headers, captions, borders, and responsive behavior to your tables. Level up your web development skills and create well-organized and visually appealing tables with HTML.

  12. HTML Tables

    HTML Table Tag & Attributes. You can make some changes in Table styles using given attributes. For example, above simple html table program have a border attribute that draws border around the table. Here, is the list of common table attributes. HTML Table Attributes

  13. Mastering the Table Tag in HTML: A Comprehensive Guide

    The table tag is at the heart of HTML's table structure. It consists of several sub-elements that work together to create a comprehensive table layout. Let's break down the essential components:

  14. HTML table advanced features and accessibility

    In the second article in this module, we look at some more advanced features of HTML tables — such as captions/summaries and grouping your rows into table head, body and footer sections — as well as looking at the accessibility of tables for visually impaired users. The basics of HTML (see Introduction to HTML ).

  15. HTML <table> Tag

    Output: Example 2: The example shows the implementation table tag by using rowspan and colspan with Custom CSS Style for background-color, right align, and border-collapse.

  16. How to Create Table in HTML?

    HTML tables are essential for organizing and displaying data in a structured format on web pages. Creating a table in HTML is a fundamental skill for web developers. It is used for product information, presenting data analytics, or designing a pricing comparison chart, etc. This article provides a step-by-step guide on how to create tables in HTML.

  17. 12 beautiful HTML table examples for beginners to practice

    These examples will help users to understand following scenerios: 1) HTML table Border. 2) HTML table Alternate Row background color. 3) HTML table Alternate Column background color. 4) HTML table Cellpading. 5) HTML table Cellspacing. 6) HTML table RowSpan.

  18. PDF Chapter 4. HTML Tables

    code in the next page. Save this as tab_ex4.html. One extra HTML tag needs to be introduced: the TH tag, which inserts a table header cell. It is similar to the TD tag and has the same attributes (i.e. align, bgcolor, height etc.). However, TH is used to set the cell's text apart from the rest of the table's text, usually setting

  19. HTML All Exercises & Assignments

    HTML All Exercises & Assignments - Tutorials ClassIf you are seeking HTML assignment help, you can find a variety of exercises and solutions on this webpage. You can practice HTML basics, tags, attributes, forms, tables, and more. Learn HTML by doing these assignments and improve your web development skills.

  20. HTML Exercises

    We have gathered a variety of HTML exercises (with answers) for each HTML Chapter. Try to solve an exercise by editing some code. Get a "hint" if you're stuck, or show the answer to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed.

  21. Basic HTML Page layout using table tag

    A HTML layout contains multiple sections & columns. Learn how to create Basic HTML Page layout using table tag. Download HTML Table layout Program Code here

  22. HTML Tables Question Bank

    Which attribute of the < table > tag is used to set an image in the background of a table? bgcolor; background; frame; rules; Ans. 2. The attribute used to specify the background cofor of a table is. ... To set image as background of an HTML table, you can use _____ attribute. Ans. background. By default, color of a table is _____