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.

  • 90% Refund @Courses
  • HTML Tutorial
  • HTML Interview Questions
  • HTML Attributes
  • HTML Examples
  • HTML Cheat Sheet
  • HTML Color Picker
  • HTML Formatter
  • HTML Projects

Related Articles

  • Solve Coding Problems
  • HTML Introduction
  • HTML Editors
  • HTML Basics
  • HTML Comments
  • HTML Elements
  • HTML Heading
  • HTML Paragraphs
  • HTML Text Formatting
  • HTML Quotations
  • HTML Colors
  • HTML Images
  • HTML Favicon

HTML Tables

  • HTML Ordered Lists
  • HTML Unordered Lists
  • HTML Description Lists
  • HTML Block and Inline Elements
  • HTML Iframes
  • HTML File Paths
  • HTML Layout
  • HTML Computer Code Elements
  • HTML5 Semantics
  • HTML Entities
  • HTML Symbols
  • HTML Emojis
  • HTML Charsets
  • HTML URL Encoding
  • HTML Responsive Web Design
  • HTML5 Video

HTML Graphics

  • SVG Tutorial

HTML Tutorial References

  • HTML Tags - A to Z List
  • HTML Attributes Complete Reference
  • HTML Global Attributes
  • HTML5 Complete Reference
  • HTML5 MathML Complete Reference
  • HTML DOM Complete Reference
  • HTML DOM Audio/Video Complete Reference
  • SVG Element Complete Reference
  • SVG Attribute Complete Reference
  • SVG Property Complete Reference
  • HTML Canvas Complete Reference

What is HTML Table ?

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.

Table of Content

Basic Example of HTML Table

Tags used in html tables, defining tables in html, adding a border to an html table, adding collapsed borders in an html table, adding cell padding in an html table, adding left align headings in an html table, adding border spacing in an html table, adding cells that span many columns in html tables, adding cells that span many rows in html tables, adding a caption in an html table, adding a background colour to the table, creating nested tables, supported browsers.

HTML Table Example

An HTML table is defined with the “table” tag. Each table row is defined with the “tr” tag. A table header is defined with the “th” tag. By default, table headings are bold and centered. A table data/cell is defined with the “td” tag.

Table Cells

Table Cell are the building blocks for defining the Table. It is denoted with <td> as a start tag & </td> as a end tag.

The rows can be formed with the help of combination of Table Cells. It is denoted by <tr> and </tr> tag as a start & end tags.

Table Headers

The Headers are generally use to provide the Heading. The Table Headers can also be used to add the heading to the Table. This contains the <th> & </th> tags.

Example 1: Creating a simple table in HTML using a table tag. 

html table task

A border is set using the CSS border property. If you do not specify a border for the table, it will be displayed without borders.

Example : Addition of the border to the HTML Table.

html table task

For borders to collapse into one border, add the CSS border-collapse property.

Example: Addition of Collapsed Borders in HTML.

html table task

Cell padding specifies the space between the cell content and its borders. If we do not specify a padding, the table cells will be displayed without padding.

Example: Addition of Table cell padding in HTML.

html table task

By default, the table headings are bold and centered. To left-align the table headings, we must use the CSS text-align property.

Example: Explains the text-align property where the text is aligned to the left.

html table task

Border spacing specifies the space between the cells. To set the border-spacing for a table, we must use the CSS border-spacing property.

Example: Explains the border space property to make the space between the Table cells.

html table task

To make a cell span more than one column, we must use the colspan attribute.

Example: Use of colspan attribute in HTML.

html table task

To make a cell span more than one row, we must use the rowspan attribute.

Example: Use of the rowspan attribute in HTML.

html table task

To add a caption to a table, we must use the “caption” tag.

Example: HTML Table caption by specifying the CSS properties for setting its width.

html table task

A color can be added as a background in an HTML table using the “ background-color ” option.

Example: Addition of the Table background color in HTML.

html table task

Nesting tables simply means making a Table inside another Table. Nesting tables can lead to complex tables layouts, which are visually interesting and have the potential of introducing errors. 

Example: Nesting of HTML Table.

html table task

  • Google Chrome 15

HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now !

Please Login to comment...

  • HTML and XML
  • HTML-Basics
  • Web technologies-HTML and XML
  • Web Technologies
  • Sahil_Chhabra
  • yashpandey2002
  • ysachin2314
  • arorakashish0911
  • bhaskargeeksforgeeks
  • bijaybhaskar
  • hardikkoriintern
  • kumargaurav97520
  • pankaj_gupta_gfg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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.

html table task

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 ....

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

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

Exploring the Power of the Video Tag in HTML - A Comprehensive Guide

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

Unleashing the Power of HTML5 Audio Player: A Comprehensive Guide

Unleashing the Power of HTML5 Audio Player: A Comprehensive Guide

Leave a reply cancel reply.

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

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

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
  • Introduction to tables
  • Table directionality
  • Table Captions: The CAPTION element
  • Row groups: the THEAD , TFOOT , and TBODY elements
  • The COLGROUP element
  • The COL element
  • Calculating the number of columns in a table
  • Calculating the width of columns
  • Table rows: The TR element
  • Cells that span several rows or columns
  • Borders and rules
  • Inheritance of alignment specifications
  • Cell margins
  • Associating header information with data cells
  • Categorizing cells
  • Algorithm to find heading information
  • Sample table

11.1 Introduction to tables

The HTML table model allows authors to arrange data -- text, preformatted text, images, links, forms, form fields, other tables, etc. -- into rows and columns of cells.

Each table may have an associated caption (see the CAPTION element) that provides a short description of the table's purpose. A longer description may also be 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, respectively). Row groups convey additional structural information and may be rendered by user agents in ways that emphasize this structure. User agents may exploit the head/body/foot division to support scrolling of body sections independently of the head and foot sections. When long tables are printed, the head and foot information may be repeated on each page that contains table data.

Authors may also group columns to provide additional structural information that may be exploited by user agents. Furthermore, authors may declare column properties at the start of a table definition (via the COLGROUP and COL elements) in a way that enables user agents to render the table incrementally rather than having to wait for all the table data to arrive before rendering.

Table cells may either contain "header" information (see the TH element) or "data" (see the TD element). Cells may span multiple rows and columns. The HTML 4 table model allows authors to label each cell so that non-visual user agents may more easily communicate heading information about the cell to the user. Not only do these mechanisms greatly assist users with visual disabilities, they make it possible for multi-modal wireless browsers with limited display capabilities (e.g., Web-enabled pagers and phones) to handle tables.

Tables should not be used purely as a means to layout document content as this may present problems when rendering to non-visual media. Additionally, when used with graphics, these tables may force users to scroll horizontally to view a table designed on a system with a larger display. To minimize these problems, authors should use style sheets to control layout rather than tables.

Note. This specification includes more detailed information about tables in sections on table design rationale and implementation issues .

Here's a simple table that illustrates some of the features of the HTML table model. The following table definition:

might be rendered something like this on a tty device:

or like this by a graphical user agent:

11.2 Elements for constructing tables

11.2.1 the table element.

Start tag: required , End tag: required

Attribute definitions

  • left: The table is to the left of the document.
  • center: The table is to the center of the document.
  • right: The table is to the right of the document.

Attributes defined elsewhere

  • id , class ( document-wide identifiers )
  • lang ( language information ), dir ( text direction )
  • title ( element title )
  • style ( inline style information )
  • onclick , ondblclick , onmousedown , onmouseup , onmouseover , onmousemove , onmouseout , onkeypress , onkeydown , onkeyup ( intrinsic events )
  • bgcolor ( background color )
  • frame , rules , border ( borders and rules )
  • cellspacing , cellpadding ( cell margins )

The TABLE element contains all other elements that specify caption, rows, content, and formatting.

The following informative list describes what operations user agents may carry out when rendering a table:

  • Make the table summary available to the user. Authors should provide a summary of a table's content and structure so that people using non-visual user agents may better understand it.
  • Render the caption, if one is defined.
  • Render the table header, if one is specified. Render the table footer, if one is specified. User agents must know where to render the header and footer. For instance, if the output medium is paged, user agents may put the header at the top of each page and the footer at the bottom. Similarly, if the user agent provides a mechanism to scroll the rows, the header may appear at the top of the scrolled area and the footer at the bottom.
  • Calculate the number of columns in the table. Note that the number of rows in a table is equal to the number of TR elements contained by the TABLE element.
  • Group the columns according to any column group specifications.
  • Render the cells, row by row and grouped in appropriate columns, between the header and footer. Visual user agents should format the table according to HTML attributes and style sheet specification.

The HTML table model has been designed so that, with author assistance, user agents may render tables incrementally (i.e., as table rows arrive) rather than having to wait for all the data before beginning to render.

In order for a user agent to format a table in one pass, authors must tell the user agent:

  • The number of columns in the table. Please consult the section on calculating the number of columns in a table for details on how to supply this information.
  • The widths of these columns. Please consult the section on calculating the width of columns for details on how to supply this information.

More precisely, a user agent may render a table in a single pass when the column widths are specified using a combination of COLGROUP and COL elements. If any of the columns are specified in relative or percentage terms (see the section on calculating the width of columns ), authors must also specify the width of the table itself.

Table directionality  

The directionality of a table is either the inherited directionality (the default is left-to-right) or that specified by the dir attribute for the TABLE element.

For a left-to-right table, column zero is on the left side and row zero is at the top. For a right-to-left table, column zero is on the right side and row zero is at the top.

When a user agent allots extra cells to a row (see the section on calculating the number of columns in a table ), extra row cells are added to the right of the table for left-to-right tables and to the left side for right-to-left tables.

Note that TABLE is the only element on which dir reverses the visual order of the columns; a single table row ( TR ) or a group of columns ( COLGROUP ) cannot be independently reversed.

When set for the TABLE element, the dir attribute also affects the direction of text within table cells (since the dir attribute is inherited by block-level elements).

To specify a right-to-left table, set the dir attribute as follows:

The direction of text in individual cells can be changed by setting the dir attribute in an element that defines the cell. Please consult the section on bidirectional text for more information on text direction issues.

11.2.2 Table Captions: The CAPTION element

  • top: The caption is at the top of the table. This is the default value.
  • bottom: The caption is at the bottom of the table.
  • left: The caption is at the left of the table.
  • right: The caption is at the right of the table.

When present, the CAPTION element's text should describe the nature of the table. The CAPTION element is only permitted immediately after the TABLE start tag. A TABLE element may only contain one CAPTION element.

Visual user agents allow sighted people to quickly grasp the structure of the table from the headings as well as the caption. A consequence of this is that captions will often be inadequate as a summary of the purpose and structure of the table from the perspective of people relying on non-visual user agents.

Authors should therefore take care to provide additional information summarizing the purpose and structure of the table using the summary attribute of the TABLE element. This is especially important for tables without captions. Examples below illustrate the use of the summary attribute.

Visual user agents should avoid clipping any part of the table including the caption, unless a means is provided to access all parts, e.g., by horizontal or vertical scrolling. We recommend that the caption text be wrapped to the same width as the table. (See also the section on recommended layout algorithms .)

11.2.3 Row groups: the THEAD , TFOOT , and TBODY elements

Start tag: required , End tag: optional

Start tag: optional , End tag: optional

  • align , char , charoff , valign ( cell alignment )

Table rows may be grouped into a table head, table foot, and one or more table body sections, using the THEAD , TFOOT and TBODY elements, respectively. This division enables user agents to support scrolling of table bodies independently of the table head and foot. When long tables are printed, the table head and foot information may be repeated on each page that contains table data.

The table head and table foot should contain information about the table's columns. The table body should contain rows of table data.

When present, each THEAD , TFOOT , and TBODY contains a row group . Each row group must contain at least one row, defined by the TR element.

This example illustrates the order and structure of table heads, feet, and bodies.

TFOOT must appear before TBODY within a TABLE definition so that user agents can render the foot before receiving all of the (potentially numerous) rows of data. The following summarizes which tags are required and which may be omitted:

  • The TBODY start tag is always required except when the table contains only one table body and no table head or foot sections. The TBODY end tag may always be safely omitted.
  • The start tags for THEAD and TFOOT are required when the table head and foot sections are present respectively, but the corresponding end tags may always be safely omitted.

Conforming user agent parsers must obey these rules for reasons of backward compatibility.

The table of the previous example could be shortened by removing certain end tags, as in:

The THEAD , TFOOT , and TBODY sections must contain the same number of columns.

11.2.4 Column groups: the COLGROUP and COL elements

Column groups allow authors to create structural divisions within a table. Authors may highlight this structure through style sheets or HTML attributes (e.g., the rules attribute for the TABLE element). For an example of the visual presentation of column groups, please consult the sample table .

A table may either contain a single implicit column group (no COLGROUP element delimits the columns) or any number of explicit column groups (each delimited by an instance of the COLGROUP element).

The COL element allows authors to share attributes among several columns without implying any structural grouping. The "span" of the COL element is the number of columns that will share the element's attributes.

The COLGROUP element  

  • In the absence of a span attribute, each COLGROUP defines a column group containing one column.
  • If the span attribute is set to N > 0, the current COLGROUP element defines a column group containing N columns.

User agents must ignore this attribute if the COLGROUP element contains one or more COL elements.

This attribute specifies a default width for each column in the current column group. In addition to the standard pixel, percentage, and relative values, this attribute allows the special form "0*" (zero asterisk) which means that the width of the each column in the group should be the minimum width necessary to hold the column's contents. This implies that a column's entire contents must be known before its width may be correctly computed. Authors should be aware that specifying "0*" will prevent visual user agents from rendering a table incrementally.

This attribute is overridden for any column in the column group whose width is specified via a COL element.

The COLGROUP element creates an explicit column group. The number of columns in the column group may be specified in two, mutually exclusive ways:

  • The element's span attribute (default value 1) specifies the number of columns in the group.
  • Each COL element in the COLGROUP represents one or more columns in the group.

The advantage of using the span attribute is that authors may group together information about column widths. Thus, if a table contains forty columns, all of which have a width of 20 pixels, it is easier to write:

When it is necessary to single out a column (e.g., for style information, to specify width information, etc.) within a group, authors must identify that column with a COL element. Thus, to apply special style information to the last column of the previous table, we single it out as follows:

The width attribute of the COLGROUP element is inherited by all 40 columns. The first COL element refers to the first 39 columns (doing nothing special to them) and the second one assigns an id value to the fortieth column so that style sheets may refer to it.

The table in the following example contains two column groups. The first column group contains 10 columns and the second contains 5 columns. The default width for each column in the first column group is 50 pixels. The width of each column in the second column group will be the minimum required for that column.

The COL element  

Start tag: required , End tag: forbidden

The COL element allows authors to group together attribute specifications for table columns. The COL does not group columns together structurally -- that is the role of the COLGROUP element. COL elements are empty and serve only as a support for attributes. They may appear inside or outside an explicit column group (i.e., COLGROUP element).

The width attribute for COL refers to the width of each column in the element's span.

Calculating the number of columns in a table  

There are two ways to determine the number of columns in a table (in order of precedence):

  • For each COL element, take the value of its span attribute (default value 1).
  • For each COLGROUP element containing at least one COL element, ignore the span attribute for the COLGROUP element. For each COL element, perform the calculation of step 1.
  • For each empty COLGROUP element, take the value of its span attribute (default value 1).
  • Otherwise, if the TABLE element contains no COLGROUP or COL elements, user agents should base the number of columns on what is required by the rows. The number of columns is equal to the number of columns required by the row with the most columns, including cells that span multiple columns. For any row that has fewer than this number of columns, the end of that row should be padded with empty cells. The "end" of a row depends on the table directionality .

It is an error if a table contains COLGROUP or COL elements and the two calculations do not result in the same number of columns.

Once the user agent has calculated the number of columns in the table, it may group them into column groups.

For example, for each of the following tables, the two column calculation methods should result in three columns. The first three tables may be rendered incrementally.

Calculating the width of columns  

Authors may specify column widths in three ways:

However, if the table does not have a fixed width, user agents must receive all table data before they can determine the horizontal space required by the table. Only then may this space be allotted to proportional columns.

If an author specifies no width information for a column, a user agent may not be able to incrementally format the table since it must wait for the entire column of data to arrive in order to allot an appropriate width.

If column widths prove to be too narrow for the contents of a particular table cell, user agents may choose to reflow the table.

The table in this example contains six columns. The first one does not belong to an explicit column group. The next three belong to the first explicit column group and the last two belong to the second explicit column group. This table cannot be formatted incrementally since it contains proportional column width specifications and no value for the width attribute for the TABLE element.

Once the (visual) user agent has received the table's data: the available horizontal space will be alloted by the user agent as follows: First the user agent will allot 30 pixels to columns one and two. Then, the minimal space required for the third column will be reserved. The remaining horizontal space will be divided into six equal portions (since 2* + 1* + 3* = 6 portions). Column four (2*) will receive two of these portions, column five (1*) will receive one, and column six (3*) will receive three.

We have set the value of the align attribute in the third column group to "center". All cells in every column in this group will inherit this value, but may override it. In fact, the final COL does just that, by specifying that every cell in the column it governs will be aligned along the ":" character.

In the following table, the column width specifications allow the user agent to format the table incrementally:

The first ten columns will be 15 pixels wide each. The last two columns will each receive half of the remaining 50 pixels. Note that the COL elements appear only so that an id value may be specified for the last two columns.

Note. Although the width attribute on the TABLE element is not deprecated, authors are encouraged to use style sheets to specify table widths.

11.2.5 Table rows: The TR element

The TR elements acts as a container for a row of table cells. The end tag may be omitted.

This sample table contains three rows, each begun by the TR element:

11.2.6 Table cells: The TH and TD elements

  • row: The current cell provides header information for the rest of the row that contains it (see also the section on table directionality ).
  • col: The current cell provides header information for the rest of the column that contains it.
  • rowgroup: The header cell provides header information for the rest of the row group that contains it.
  • colgroup: The header cell provides header information for the rest of the column group that contains it.

Table cells may contain two types of information: header information and data. This distinction enables user agents to render header and data cells distinctly, even in the absence of style sheets. For example, visual user agents may present header cell text with a bold font. Speech synthesizers may render header information with a distinct voice inflection.

The TH element defines a cell that contains header information. User agents have two pieces of header information available: the contents of the TH element and the value of the abbr attribute. User agents must render either the contents of the cell or the value of the abbr attribute. For visual media, the latter may be appropriate when there is insufficient space to render the full contents of the cell. For non-visual media abbr may be used as an abbreviation for table headers when these are rendered along with the contents of the cells to which they apply.

The headers and scope attributes also allow authors to help non-visual user agents process header information. Please consult the section on labeling cells for non-visual user agents for information and examples.

The TD element defines a cell that contains data.

Cells may be empty (i.e., contain no data).

For example, the following table contains four columns of data, each headed by a column description.

A user agent rendering to a tty device might display this as follows:

Cells that span several rows or columns  

Cells may span several rows or columns. The number of rows or columns spanned by a cell is set by the rowspan and colspan attributes for the TH and TD elements.

In this table definition, we specify that the cell in row four, column two should span a total of three columns, including the current column.

This table might be rendered on a tty device by a visual user agent as follows:

The next example illustrates (with the help of table borders) how cell definitions that span more than one row or column affect the definition of later cells. Consider the following table definition:

As cell "2" spans the first and second rows, the definition of the second row will take it into account. Thus, the second TD in row two actually defines the row's third cell. Visually, the table might be rendered to a tty device as:

while a graphical user agent might render this as:

Note that if the TD defining cell "6" had been omitted, an extra empty cell would have been added by the user agent to complete the row.

Similarly, in the following table definition:

cell "4" spans two columns, so the second TD in the row actually defines the third cell ("6"):

A graphical user agent might render this as:

Defining overlapping cells is an error. User agents may vary in how they handle this error (e.g., rendering may vary).

The following illegal example illustrates how one might create overlapping cells. In this table, cell "5" spans two rows and cell "7" spans two columns, so there is overlap in the cell between "7" and "9":

11.3 Table formatting by visual user agents

Note. The following sections describe the HTML table attributes that concern visual formatting. When this specification was first published in 1997, [CSS1] did not offer mechanisms to control all aspects of visual table formatting. Since then, [CSS2] has added properties to allow visual formatting of tables.

HTML 4 includes mechanisms to control:

  • border styles
  • horizontal and vertical alignment of cell contents
  • and cell margins

11.3.1 Borders and rules

The following attributes affect a table's external frame and internal rules.

  • void: No sides. This is the default value.
  • above: The top side only.
  • below: The bottom side only.
  • hsides: The top and bottom sides only.
  • vsides: The right and left sides only.
  • lhs: The left-hand side only.
  • rhs: The right-hand side only.
  • box: All four sides.
  • border: All four sides.
  • none: No rules. This is the default value.
  • groups: Rules will appear between row groups (see THEAD , TFOOT , and TBODY ) and column groups (see COLGROUP and COL ) only.
  • rows: Rules will appear between rows only.
  • cols: Rules will appear between columns only.
  • all: Rules will appear between all rows and columns.

To help distinguish the cells of a table, we can set the border attribute of the TABLE element. Consider a previous example:

In the following example, the user agent should show borders five pixels thick on the left-hand and right-hand sides of the table, with rules drawn between each column.

The following settings should be observed by user agents for backwards compatibility.

  • Setting border ="0" implies frame ="void" and, unless otherwise specified, rules ="none".
  • Other values of border imply frame ="border" and, unless otherwise specified, rules ="all".
  • The value "border" in the start tag of the TABLE element should be interpreted as the value of the frame attribute. It implies rules ="all" and some default (non-zero) value for the border attribute.

For example, the following definitions are equivalent:

as are the following:

Note. The border attribute also defines the border behavior for the OBJECT and IMG elements, but takes different values for those elements.

11.3.2 Horizontal and vertical alignment

The following attributes may be set for different table elements (see their definitions).

  • left: Left-flush data/Left-justify text. This is the default value for table data.
  • center: Center data/Center-justify text. This is the default value for table headers.
  • right: Right-flush data/Right-justify text.
  • justify: Double-justify text.
  • char: Align text around a specific character. If a user agent doesn't support character alignment, behavior in the presence of this value is unspecified.
  • top: Cell data is flush with the top of the cell.
  • middle: Cell data is centered vertically within the cell. This is the default value.
  • bottom: Cell data is flush with the bottom of the cell.
  • baseline: All cells in the same row as a cell whose valign attribute has this value should have their textual data positioned so that the first text line occurs on a baseline common to all cells in the row. This constraint does not apply to subsequent text lines in these cells.

When charoff is used to set the offset of an alignment character, the direction of offset is determined by the current text direction (set by the dir attribute). In left-to-right texts (the default), offset is from the left margin. In right-to-left texts, offset is from the right margin. User agents are not required to support this attribute.

The table in this example aligns a row of currency values along a decimal point. We set the alignment character to "." explicitly.

The formatted table may resemble the following:

When the contents of a cell contain more than one instance of the alignment character specified by char and the contents wrap, user agent behavior is undefined. Authors should therefore be attentive in their use of char .

Note. Visual user agents typically render TH elements vertically and horizontally centered within the cell and with a bold font weight.

Inheritance of alignment specifications  

The alignment of cell contents can be specified on a cell by cell basis, or inherited from enclosing elements, such as the row, column or the table itself.

The order of precedence (from highest to lowest) for the attributes align , char , and charoff is the following:

  • An alignment attribute set on an element within a cell's data (e.g., P ).
  • An alignment attribute set on a cell ( TH and TD ).
  • An alignment attribute set on a column grouping element ( COL and COLGROUP ). When a cell is part of a multi-column span, the alignment property is inherited from the cell definition at the beginning of the span.
  • An alignment attribute set on a row or row grouping element ( TR , THEAD , TFOOT , and TBODY ). When a cell is part of a multi-row span, the alignment property is inherited from the cell definition at the beginning of the span.
  • An alignment attribute set on the table ( TABLE ).
  • The default alignment value.

The order of precedence (from highest to lowest) for the attribute valign (as well as the other inherited attributes lang , dir , and style ) is the following:

  • An attribute set on an element within a cell's data (e.g., P ).
  • An attribute set on a cell ( TH and TD ).
  • An attribute set on a row or row grouping element ( TR , THEAD , TFOOT , and TBODY ). When a cell is part of a multi-row span, the attribute value is inherited from the cell definition at the beginning of the span.
  • An attribute set on a column grouping element ( COL and COLGROUP ). When a cell is part of a multi-column span, the attribute value is inherited from the cell definition at the beginning of the span.
  • An attribute set on the table ( TABLE ).
  • The default attribute value.

Furthermore, when rendering cells, horizontal alignment is determined by columns in preference to rows, while for vertical alignment, rows are given preference over columns.

The default alignment for cells depends on the user agent. However, user agents should substitute the default attribute for the current directionality (i.e., not just "left" in all cases).

User agents that do not support the "justify" value of the align attribute should use the value of the inherited directionality in its place.

11.3.3 Cell margins

These two attributes control spacing between and within cells. The following illustration explains how they relate:

In the following example, the cellspacing attribute specifies that cells should be separated from each other and from the table frame by twenty pixels. The cellpadding attribute specifies that the top margin of the cell and the bottom margin of the cell will each be separated from the cell's contents by 10% of the available vertical space (the total being 20%). Similarly, the left margin of the cell and the right margin of the cell will each be separated from the cell's contents by 10% of the available horizontal space (the total being 20%).

If a table or given column has a fixed width, cellspacing and cellpadding may demand more space than assigned. User agents may give these attributes precedence over the width attribute when a conflict occurs, but are not required to.

11.4 Table rendering by non-visual user agents

11.4.1 associating header information with data cells.

Non-visual user agents such as speech synthesizers and Braille-based devices may use the following TD and TH element attributes to render table cells more intuitively:

  • For a given data cell, the headers attribute lists which cells provide pertinent header information. For this purpose, each header cell must be named using the id attribute. Note that it's not always possible to make a clean division of cells into headers or data. You should use the TD element for such cells together with the id or scope attributes as appropriate.
  • For a given header cell , the scope attribute tells the user agent the data cells for which this header provides information. Authors may choose to use this attribute instead of headers according to which is more convenient; the two attributes fulfill the same function. The headers attribute is generally needed when headers are placed in irregular positions with respect to the data they apply to.
  • The abbr attribute specifies an abbreviated header for header cells so that user agents may render header information more rapidly.

In the following example, we assign header information to cells by setting the headers attribute. Each cell in the same column refers to the same header cell (via the id attribute).

A speech synthesizer might render this table as follows:

Note how the header "Type of Coffee" is abbreviated to "Type" using the abbr attribute.

Here is the same example substituting the scope attribute for the headers attribute. Note the value "col" for the scope attribute, meaning "all cells in the current column":

Here's a somewhat more complex example illustrating other values for the scope attribute:

Note the use of the scope attribute with the "row" value. Although the first cell in each row contains data, not header information, the scope attribute makes the data cell behave like a row header cell. This allows speech synthesizers to provide the relevant course name upon request or to state it immediately before each cell's content.

11.4.2 Categorizing cells

Users browsing a table with a speech-based user agent may wish to hear an explanation of a cell's contents in addition to the contents themselves. One way the user might provide an explanation is by speaking associated header information before speaking the data cell's contents (see the section on associating header information with data cells ).

Users may also want information about more than one cell, in which case header information provided at the cell level (by headers , scope , and abbr ) may not provide adequate context. Consider the following table, which classifies expenses for meals, hotels, and transport in two locations (San Jose and Seattle) over several days:

Users might want to extract information from the table in the form of queries:

  • "What did I spend for all my meals?"
  • "What did I spend for meals on 25 August?"
  • "What did I spend for all expenses in San Jose?"

Each query involves a computation by the user agent that may involve zero or more cells. In order to determine, for example, the costs of meals on 25 August, the user agent must know which table cells refer to "Meals" (all of them) and which refer to "Dates" (specifically, 25 August), and find the intersection of the two sets.

To accommodate this type of query, the HTML 4 table model allows authors to place cell headers and data into categories. For example, for the travel expense table, an author could group the header cells "San Jose" and "Seattle" into the category "Location", the headers "Meals", "Hotels", and "Transport" in the category "Expenses", and the four days into the category "Date". The previous three questions would then have the following meanings:

  • "What did I spend for all my meals?" means "What are all the data cells in the "Expenses=Meals" category?
  • "What did I spend for meals on 25 August?" means "What are all the data cells in the "Expenses=Meals" and "Date=Aug-25-1997" categories?
  • "What did I spend for all expenses in San Jose?" means "What are all the data cells in the "Expenses=Meals, Hotels, Transport" and "Location=San Jose" categories?

Authors categorize a header or data cell by setting the axis attribute for the cell. For instance, in the travel expense table, the cell containing the information "San Jose" could be placed in the "Location" category as follows:

Any cell containing information related to "San Jose" should refer to this header cell via either the headers or the scope attribute. Thus, meal expenses for 25-Aug-1997 should be marked up to refer to id attribute (whose value here is "a6") of the "San Jose" header cell:

Each headers attribute provides a list of id references. Authors may thus categorize a given cell in any number of ways (or, along any number of "headers", hence the name).

Below we mark up the travel expense table with category information:

Note that marking up the table this way also allows user agents to avoid confusing the user with unwanted information. For instance, if a speech synthesizer were to speak all of the figures in the "Meals" column of this table in response to the query "What were all my meal expenses?", a user would not be able to distinguish a day's expenses from subtotals or totals. By carefully categorizing cell data, authors allow user agents to make important semantic distinctions when rendering.

Of course, there is no limit to how authors may categorize information in a table. In the travel expense table, for example, we could add the additional categories "subtotals" and "totals".

This specification does not require user agents to handle information provided by the axis attribute, nor does it make any recommendations about how user agents may present axis information to users or how users may query the user agent about this information.

However, user agents, particularly speech synthesizers, may want to factor out information common to several cells that are the result of a query. For instance, if the user asks "What did I spend for meals in San Jose?", the user agent would first determine the cells in question (25-Aug-1997: 37.74, 26-Aug-1997:27.28), then render this information. A user agent speaking this information might read it:

or, more compactly:

An even more economical rendering would factor the common information and reorder it:

User agents that support this type of rendering should allow user agents a means to customize rendering (e.g., through style sheets).

11.4.3 Algorithm to find heading information

In the absence of header information from either the scope or headers attribute, user agents may construct header information according to the following algorithm. The goal of the algorithm is to find an ordered list of headers. (In the following description of the algorithm the table directionality is assumed to be left-to-right.)

  • First, search left from the cell's position to find row header cells. Then search upwards to find column header cells. The search in a given direction stops when the edge of the table is reached or when a data cell is found after a header cell.
  • Row headers are inserted into the list in the order they appear in the table. For left-to-right tables, headers are inserted from left to right.
  • Column headers are inserted after row headers, in the order they appear in the table, from top to bottom.
  • If a header cell has the headers attribute set, then the headers referenced by this attribute are inserted into the list and the search stops for the current direction.
  • TD cells that set the axis attribute are also treated as header cells.

11.5 Sample table

This sample illustrates grouped rows and columns. The example is adapted from "Developing International Software", by Nadine Kano.

In "ascii art", the following table:

would be rendered something like this:

This example illustrates how COLGROUP can be used to group columns and set the default column alignment. Similarly, TBODY is used to group rows. The frame and rules attributes tell the user agent which borders and rules to render.

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

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

HTML Tables | How to use the HTML <table> Tag

autumn leaves blowing past computer

Ever wondered how HTML tables can transform your web pages? You’re in the right place! HTML tables are more than just data display tools. They structure data in a way that enhances user experience and adds depth to your web pages. To help you grasp this, let’s use an analogy: think of an HTML table as a spreadsheet. It’s a grid that organizes data into rows and columns, making it digestible and easy to navigate.

This comprehensive guide will help you delve into the world of HTML tables, from understanding their anatomy to exploring their varied applications. Whether you’re a seasoned developer or a beginner, there’s something here for you. Let’s master the art of HTML tables together!

TL;DR: What is an HTML table?

An HTML table is a powerful tool used in web development to structure and present data in a tabular format. It’s a grid of cells, organized into rows and columns, that makes data easy to read and understand. Here is a basic example:

Table of Contents

HTML Tables and Their Purpose

Significance of table header cells, html tables in real-world applications, table header cells: enhancing data representation, the rigidity of html tables: a strength, the context providers: row and column headers, the scope attribute: a hidden gem, user experience enhancement with the scope attribute, css in html tables: the game changer, html vs css: a division of labor, css stylesheet: enhancing table readability, html and css: a synergistic table creation, misuse of html tables in web page layouts, the downside of using tables for layout, the emergence of css layout techniques, the right tool for the right task, mastering html tables: knowing their limits, conclusion: the art of mastering html tables.

HTML tables, inherent in HTML (HyperText Markup Language), are tools to structure and present tabular data on a webpage. An HTML table is essentially a grid of cells, neatly organized into rows and columns, facilitating a structured format for data, enhancing readability, and understanding for users. Primarily, HTML tables display data in a tabular format, proving particularly useful when a side-by-side comparison of items is required.

A vital component of an HTML table is the table header cell, created using the <th> tag. Header cells are significant as they provide context for the data in the rows beneath them. For instance, in an HTML table displaying a product list with prices, the header cells might contain ‘Product’ and ‘Price’.

Example of table header cells:

Enhancing the readability of your HTML tables can be achieved by styling these header cells. With CSS (Cascading Style Sheets), you can modify the header cells’ background color, font size, font weight, and more to make them stand out and guide the reader effectively.

HTML tables find use in a wide array of applications, especially when presenting numerical data like statistics or financial information. A business might use an HTML table on their website to showcase their quarterly sales data, while a sports website might employ an HTML table to display the latest league standings.

Table header cells significantly enhance data representation effectiveness in HTML tables by providing context to the data, simplifying users’ understanding of what the data represents. Without header cells, users would have to guess the representation of each data column, potentially leading to confusion and data misinterpretation.

Mastering the structure and nuances of HTML tables, such as the importance of table header cells, can significantly enhance data readability and accessibility, enabling the creation of effective and user-friendly HTML tables.

HTML tables, in contrast to other HTML elements, possess an inherent rigidity. This characteristic, while seemingly a limitation, is one of their most significant strengths. The rows and columns of an HTML table maintain their positions, providing a stable structure for data representation. This structural stability ensures consistency in data presentation across different platforms and devices.

Row and column headers in HTML tables serve as critical context providers for the data. They label the data in a manner that simplifies user understanding. Typically, row headers categorize data vertically, while column headers do so horizontally. This dual categorization system enhances the versatility and efficiency of HTML tables when presenting complex data sets.

The scope attribute, while lesser-known, is an incredibly useful feature of HTML tables. Used with the <th> tag, the scope attribute clarifies the relevance of header cells. It can take two values: row or col , indicating whether the header cell applies to the row or the column, respectively.

For instance, in a table with a header cell labeled ‘Price’, the scope attribute can specify whether ‘Price’ is a header for a row or a column.

Example of scope attribute:

This clarification aids both sighted users and visually impaired users using screen readers to comprehend the table’s structure and content.

The scope attribute significantly enhances user experience by providing clarity and context to data in an HTML table. It helps users understand the relationship between header cells and data cells, making the table more navigable and readable. This is especially important for visually impaired users relying on screen readers, as the scope attribute aids the screen reader in accurately interpreting the table.

In conclusion, strategic table implementation, including the use of the scope attribute, optimizes accessibility and user experience significantly. By understanding and utilizing these features, you can create HTML tables that are not only effective but also user-friendly.

CSS, or Cascading Style Sheets, is a style sheet language that describes the look and formatting of a document written in HTML. While HTML is the backbone that structures the content, CSS is the artist that paints the presentation. In the realm of HTML tables, CSS can elevate their effectiveness, transforming them from mere functional elements to visually appealing components.

You can employ CSS to style various facets of an HTML table, such as the font, color, size, and alignment of the text, as well as the borders, padding, and background colors of the cells. This styling capability enables a high degree of customization, allowing you to craft tables that seamlessly blend with your website’s aesthetic.

Example of CSS styling in HTML table:

When crafting an HTML table, it’s crucial to comprehend the distinct roles of HTML and CSS. HTML is the architect, responsible for creating the table structure (rows, columns, cells), while CSS is the interior designer, used to style this structure. This separation of concerns fosters greater flexibility and maintainability. You can revamp your table’s look without meddling with the underlying structure, and vice versa.

To bolster the readability of your HTML tables, consider providing a minimal CSS stylesheet. This could encompass styles for striping rows (alternating the background color of each row), highlighting the row on hover, and styling the header cells for prominence. Here’s a simple example:

This CSS will enhance the readability and aesthetic appeal of your HTML tables, thereby improving the overall user experience.

Merging HTML and CSS allows you to unlock the full potential of tables. HTML provides the structure, facilitating logical and organized data arrangement. CSS, on the other hand, provides the style, enabling visually appealing data presentation. Together, they empower you to create tables that are not only functional but also beautiful and user-friendly.

In conclusion, the influence of CSS in table styling is profound. By understanding and leveraging the capabilities of CSS, you can create HTML tables that excel in data representation while being engaging and appealing to the user.

While HTML tables are excellent for displaying data, their misuse in web page layouts is often observed. In the web’s early days, developers used HTML tables as a workaround to create complex layouts due to the limited power and support of CSS. However, using tables for layout is semantically incorrect (tables are designed for tabular data, not layout) and carries several drawbacks.

Tables are inherently rigid and inflexible, making them ill-suited for responsive web design. Their inability to adapt well to different screen sizes can lead to accessibility issues. Additionally, tables add extra markup to your pages, potentially slowing down your site and negatively impacting your SEO (Search Engine Optimization).

The advent of powerful CSS layout techniques like Flexbox and Grid has minimized the misuse of HTML tables for layout. These CSS techniques enable more flexible and responsive layouts without the drawbacks associated with using tables. Furthermore, they’re semantically correct, as they’re designed specifically for creating layouts.

The transition of web page layouts from HTML tables to CSS layout techniques underlines the importance of using the right tool for the right task. While HTML tables excel in presenting tabular data, CSS is the go-to tool for creating web page layouts. Respecting the distinct roles of HTML and CSS can lead to the creation of more effective, accessible, and efficient web pages.

A crucial aspect of mastering HTML tables is understanding their limitations. While they’re indispensable for displaying tabular data, they’re not designed for creating web page layouts. Recognizing this can help avoid the pitfall of misusing HTML tables and lead to the creation of web pages that are visually appealing, semantically correct, and accessible.

In conclusion, HTML tables are a potent tool in web development, but they need to be used correctly. By understanding the pitfalls of misusing HTML tables and appreciating the benefits of using the right tool for the right task, you can create effective and user-friendly web pages.

In this comprehensive guide, we’ve journeyed through the intricate world of HTML tables. We’ve dissected their purpose and their practical applications, spotlighting the significance of table header cells. We’ve navigated the dynamics of HTML tables, discussing their inherent rigidity, the role of row and column headers, and the scope attribute’s pivotal role in enhancing user experience.

The power of CSS in table styling has been highlighted, underlining the distinct roles of HTML and CSS, and the importance of a minimal CSS stylesheet for table readability. We’ve also cautioned against the common pitfall of misusing HTML tables for web page layouts, advocating for the use of CSS layout techniques instead.

HTML tables are a potent tool for displaying tabular data on web pages. However, they demand correct usage. Misusing HTML tables can lead to accessibility issues, a poor user experience, and negative SEO impacts. However, with a thorough understanding of HTML tables’ anatomy and dynamics, and by harnessing the power of CSS, you can craft effective, accessible, and visually appealing tables.

In conclusion, mastering HTML tables goes beyond knowing how to use them – it’s about understanding when not to use them. Armed with the knowledge from this guide, you’re now prepared to harness the full potential of HTML tables in your web development journey.

About Author

Gabriel Ramuglia

Gabriel Ramuglia

Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

Related Posts

install_java_windows_screen_logo_setup

Subscribe Now

* You will receive the latest news and updates on your favorite celebrities!

Trending News

Vincent Tech Blog

Using Tables in HTML with Exercises – Lesson 1.5 

html table task

Welcome to Lesson to Lesson 1.5, in this lesson we’ll be looking at HTML Tables. We shall be under going the following, understanding of the different elements involved in making a HTML table. The following tag elements are used in making tables:

  • The  <table> tag helps to display information in a tabular format, carries the entire table.
  • The <thead>  tag, This specifies the heading of a specific table
  • The <th>  tag, This specifies a table head data of a specific table
  • The <tbody>  tag, This specifies the body of a specific table
  • The <tr> tag, helps us to  to create a row in our table,
  • The <td> tag, helps us to put data in each column of the table

The Table HTML Structure, read carefully.

[html] <table border=”1″>

<thead> <!– Head Section –> <tr> <!– Heading row –> <th>No.</th>  <!– First Column data –> <th>Name</th> <!– Second Column data –> <th>Age</th> <!– Third Column data –> </tr> </thead>

<tbody> <!– Body Section –> <tr> <!– First row –> <td>1</td> <td>Becky</td> <td>23</td> </tr>

<tr> <!– Second row –> <td>2</td> <td>Ben</td> <td>5</td> </tr>

<tr> <!– Third row –> <td>3</td> <td>Ben</td> <td>5</td> </tr>

</tbody> </table> [/html]

html table task

Note that the  <table>  tag has a  border  attribute set to ‘1’ to bring in border to the table. Although the table at this state doesn’t look the best with this view. We shall be using CSS later to style our HTML elements to look better.

Alright there we go! This is just a normal table without styling.

HTML Table Exercise

Organizing Student data using HTML table. Please ensure you read the codes and comments carefully. We’ll be using the element again, you can refer back to the beginning of this post to get the meaning of each tags

<h1>Student Records</h1> <table border=”1″> <thead> <tr> <!– Heading row –> <th>No.</th>  <!– First Column data –> <th>Image.</th>  <!– Second Column data –> <th>First Name</th> <!– Second Column data –> <th>Last Name</th> <!– Third Column data –> <th>Age</th> <!– Fourth Column data –> <th>Hubby</th> <!– Fourth Column data –> </tr> </thead> <tbody> <tr> <!– First row –> <td>1</td> <td><img src=”https://images.vexels.com/media/users/3/145743/isolated/preview/b46f965c51e1ce30b5cb485b6c9c4e03-homem-m-o-cruzou-a-ilustra–o-by-vexels.png” height=”100″ width=”100″ alt=””></td> <td>James</td> <td>Frosty</td> <td>25</td> <td><a href=”https://google.com”>Swimming</a></td> </tr> <tr> <!– Second row –> <td>2</td> <td><img src=”https://png.pngtree.com/element_origin_min_pic/17/01/01/a8c6df6c15a1ee8985ddc5d371296d2f.jpg” height=”100″ width=”100″ alt=””></td> <td>Anna</td> <td>Bayo</td> <td>23</td> <td><a href=”https://google.com”>Cooking</a> </td> </tr> <tr> <!– Third row –> <td>3</td> <td><img src=”https://png.pngtree.com/element_origin_min_pic/17/03/19/8be63cc1c4d6542e54887087a634dadd.jpg” height=”100″ width=”100″ alt=””></td> <td>James</td> <td>Lartey</td> <td>22</td> <td><a href=”https://google.com”>Rapping</a> </td> </tr> </tbody> </table>

html table task

Good Job! Now let’s move on to HTML forms in next lesson.

TOP 20 NETWORK ADMINISTRATOR INTERVIEW QUESTIONS AND ANSWERS

Understanding lists and attributes in html lesson 1.4.

html table task

Related posts

Understanding data structures and algorithms + big-o notation , building rest api with deno & postgresql – part 2 , getting started with html lesson 1.3 , fix: outdated npm packages (deprecated) in node js project , understanding front end and internet basics + environment setup lesson 1.1 , developing rest api with deno – part 1 , leave a reply cancel reply.

Save my name, email, and website in this browser for the next time I comment.

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Today's pick

How to set up a virtual machine , recon for pentesting using python (email grabbing) , svn fix trac error: no node at revision wp plugin , setup flutter on kali, ubuntu, and any other linux distro  , build a quiz app using flutter for android and ios  , 40 network protocols with port numbers, transport protocols and meanings  , ios 14: everything you need to know about apple’s new release  , subscribe for newsletter.

* You will receive the latest news and updates on your favorite topics!

flutter version downgrade

How to Downgrade Flutter Version – FIXED 

Learn how to downgrade your flutter version to a lower version, in this article we will reduce the flutter version…

resources for playstore and apple store

Generate Resources for Android Playstore & iOS Apple Store Flutter 

In this post, we’ll generate resources for the flutter app we created in the previous post. we’ll be learning how…

flutter app

Build a Quiz App using Flutter for Android and iOS 

In this post we’ll be working with Flutter, a fast-rising Developer tool built by Google to develop an Android App,…

flutter linux

Setup Flutter on Kali, Ubuntu, and any other Linux Distro 

In this post, we’ll be learning how to set up your Flutter on Linux for development. Flutter is a fast-rising…

xcode

FIXED xcodebuild: Failed to load code for plug-in – Repeatedly Being Asked to Install Command Line Tools 

Hey there, updating your MacOS Montery Xcode can be a pin in the a$$ especially when you got Xcode working…

Username or Email Address

Remember Me

Registration is closed.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Styling tables

  • Overview: Building blocks

Styling an HTML table isn't the most glamorous job in the world, but sometimes we all have to do it. This article provides a guide to making HTML tables look good, with some specific table styling techniques highlighted.

A typical HTML table

Let's start by looking at a typical HTML table. Well, I say typical — most HTML table examples are about shoes, or the weather, or employees; we decided to make things more interesting by making it about famous punk bands from the UK. The markup looks like so:

The table is nicely marked up, easily stylable, and accessible, thanks to features such as scope , <caption> , <thead> , <tbody> , etc. Unfortunately, it doesn't look good when rendered on the screen (see it live at punk-bands-unstyled.html ):

an unstyled table showing a summary of Uk's famous punk bands

With only the default browser styling it looks cramped, hard to read, and boring. We need to use some CSS to fix this up.

Styling our table

Let's work through styling our table example together.

  • To start with, make a local copy of the sample markup , download both images ( noise and leopardskin ), and put the three resulting files in a working directory somewhere on your local computer.
  • Next, create a new file called style.css and save it in the same directory as your other files.
  • Link the CSS to the HTML by placing the following line of HTML inside your <head> : html < link href = " style.css " rel = " stylesheet " />

Spacing and layout

The first thing we need to do is sort out the spacing/layout — default table styling is so cramped! To do this, add the following CSS to your style.css file:

The most important parts to note are as follows:

  • A table-layout value of fixed is generally a good idea to set on your table, as it makes the table behave a bit more predictably by default. Normally, table columns tend to be sized according to how much content they contain, which produces some strange results. With table-layout: fixed , you can size your columns according to the width of their headings, and then deal with their content as appropriate. This is why we've selected the four different headings with the thead th:nth-child(n) ( :nth-child ) selector ("Select the n-th child that is a <th> element in a sequence, inside a <thead> element") and given them set percentage widths. The entire column width follows the width of its heading, making for a nice way to size your table columns. Chris Coyier discusses this technique in more detail in Fixed Table Layouts . We've coupled this with a width of 100%, meaning that the table will fill any container it is put in, and be nicely responsive (although it would still need some more work to get it looking good on narrow screen widths).

a 2 by 2 table with default spacing between the borders showing no border collapse

  • We've put a border around the whole table, which is needed because we'll be putting some borders around the table header and footer later on — it looks really odd and disjointed when you don't have a border around the whole outside of the table and end up with gaps.
  • We've set some padding on the <th> and <td> elements — this gives the data items some space to breathe, making the table look a lot more legible.

At this point, our table already looks a lot better:

a semi-styled table with spacing to make the data more legible and showing a summary of Uk's famous punk bands

Some simple typography

Now we'll get our text sorted out a bit.

First of all, we've found a font on Google Fonts that is suitable for a table about punk bands. You can go there and find a different one if you like; you'll just have to replace our provided <link> element and custom font-family declaration with the ones Google Fonts gives you.

First, add the following <link> element into your HTML head, just above your existing <link> element:

Now add the following CSS into your style.css file, below the previous addition:

There is nothing really specific to tables here; we are generally tweaking the font styling to make things easier to read:

  • We have set a global sans-serif font stack; this is purely a stylistic choice. We've also set our custom font on the headings inside the <thead> and <tfoot> elements, for a nice grungy, punky look.
  • We've set some letter-spacing on the headings and cells, as we feel it aids readability. Again, mostly a stylistic choice.
  • We've center-aligned the text in the table cells inside the <tbody> so that they line up with the headings. By default, cells are given a text-align value of left , and headings are given a value of center , but generally it looks better to have the alignments set the same for both. The default bold weight on the heading fonts is enough to differentiate their look.
  • We've right-aligned the heading inside the <tfoot> so that it is visually associated better with its data point.

The result looks a bit neater:

a styled table with a global sans-serif font stack and good spacing to make the data more legible and showing a summary of Uk's famous punk bands

Graphics and colors

Now onto graphics and colors! Because the table is full of punk and attitude, we need to give it some bright imposing styling to suit it. Don't worry, you don't have to make your tables this loud — you can opt for something more subtle and tasteful.

Start by adding the following CSS to your style.css file, again at the bottom:

Again, there's nothing specific to tables here, but it is worthwhile to note a few things.

We've added a background-image to the <thead> and <tfoot> , and changed the color of all the text inside the header and footer to white (and given it a text-shadow ) so it is readable. You should always make sure your text contrasts well with your background, so it is readable.

We've also added a linear gradient to the <th> and <td> elements inside the header and footer for a nice bit of texture, as well as giving those elements a bright purple border. It is useful to have multiple nested elements available so you can layer styles on top of one another. Yes, we could have put both the background image and the linear gradient on the <thead> and <tfoot> elements using multiple background images, but we decided to do it separately for the benefit of older browsers that don't support multiple background images or linear gradients.

Zebra striping

We wanted to dedicate a separate section to showing you how to implement zebra stripes — alternating rows of color that make the different data rows in your table easier to parse and read. Add the following CSS to the bottom of your style.css file:

  • Earlier on you saw the :nth-child selector being used to select specific child elements. It can also be given a formula as a parameter, so it will select a sequence of elements. The formula 2n+1 would select all the odd numbered children (1, 3, 5, etc.) and the formula 2n would select all the even numbered children (2, 4, 6, etc.) We've used the odd and even keywords in our code, which do exactly the same things as the aforementioned formulae. In this case we are giving the odd and even rows different (lurid) colors.
  • We've also added a repeating background tile to all the body rows, which is just a bit of noise (a semi-transparent .png with a bit of visual distortion on it) to provide some texture.
  • Lastly, we've given the entire table a solid background color so that browsers that don't support the :nth-child selector still have a background for their body rows.

This color explosion results in the following look:

a well styled table with a repeating background in the body rows and the entire table a solid background to make the data showing a summary of Uk's famous punk bands more appealing

Now, this may be a bit over the top and not to your taste, but the point we are trying to make here is that tables don't have to be boring and academic.

Styling the caption

There is one last thing to do with our table — style the caption. To do this, add the following to the bottom of your style.css file:

There is nothing remarkable here, except for the caption-side property, which has been given a value of bottom . This causes the caption to be positioned on the bottom of the table, which along with the other declarations gives us this final look (see it live at punk-bands-complete.html ):

a white background below the styled table containing a caption of what the table is about. "a summary of Uk's famous punk bands" in this case

Table styling quick tips

Before moving on, we thought we'd provide you with a quick list of the most useful points illustrated above:

  • Make your table markup as simple as possible, and keep things flexible, e.g. by using percentages, so the design is more responsive.
  • Use table-layout : fixed to create a more predictable table layout that allows you to easily set column widths by setting width on their headings ( <th> ).
  • Use border-collapse : collapse to make table elements borders collapse into each other, producing a neater and easier to control look.
  • Use <thead> , <tbody> , and <tfoot> to break up your table into logical chunks and provide extra places to apply CSS to, so it is easier to layer styles on top of one another if required.
  • Use zebra striping to make alternative rows easier to read.
  • Use text-align to line up your <th> and <td> text, to make things neater and easier to follow.

Test your skills!

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Tables .

With styling tables now behind us, we need something else to occupy our time. The next article explores debugging CSS — how to solve problems such as layouts not looking like they should, or properties not applying when you think they should. This includes information on using browser DevTools to find solutions to your problems.

HTML Tutorial

  • HTML Tutorial
  • HTML - Home
  • HTML - Overview
  • HTML - Basic Tags
  • HTML - Elements
  • HTML - Attributes
  • HTML - Formatting
  • HTML - Phrase Tags
  • HTML - Meta Tags
  • HTML - Comments
  • HTML - Images

HTML - Tables

  • HTML - Lists
  • HTML - Text Links
  • HTML - Image Links
  • HTML - Email Links
  • HTML - Frames
  • HTML - Iframes
  • HTML - Blocks
  • HTML - Backgrounds
  • HTML - Colors
  • HTML - Fonts
  • HTML - Forms
  • HTML - Embed Multimedia
  • HTML - Marquees
  • HTML - Header
  • HTML - Style Sheet
  • HTML - Javascript
  • HTML - Layouts
  • HTML References
  • HTML - Tags Reference
  • HTML - Attributes Reference
  • HTML - Events Reference
  • HTML - Fonts Reference
  • HTML - ASCII Codes
  • ASCII Table Lookup
  • HTML - Color Names
  • HTML - Entities
  • HTML - Fonts Ref
  • HTML - Events Ref
  • MIME Media Types
  • HTML - URL Encoding
  • Language ISO Codes
  • HTML - Character Encodings
  • HTML - Deprecated Tags
  • HTML Resources
  • HTML - Quick Guide
  • HTML - Useful Resources
  • HTML - Color Code Builder
  • HTML - Online Editor
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

The HTML tables allow web authors to arrange data like text, images, links, other tables, etc. into rows and columns of cells.

The HTML tables are created using the <table> tag in which the <tr> tag is used to create table rows and <td> tag is used to create data cells. The elements under <td> are regular and left aligned by default

This will produce the following result −

Here, the border is an attribute of <table> tag and it is used to put a border across all the cells. If you do not need a border, then you can use border = "0".

Table Heading

Table heading can be defined using <th> tag. This tag will be put to replace <td> tag, which is used to represent actual data cell. Normally you will put your top row as table heading as shown below, otherwise you can use <th> element in any row. Headings, which are defined in <th> tag are centered and bold by default.

Cellpadding and Cellspacing Attributes

There are two attributes called cellpadding and cellspacing which you will use to adjust the white space in your table cells. The cellspacing attribute defines space between table cells, while cellpadding represents the distance between cell borders and the content within a cell.

Colspan and Rowspan Attributes

You will use colspan attribute if you want to merge two or more columns into a single column. Similar way you will use rowspan if you want to merge two or more rows.

Tables Backgrounds

You can set table background using one of the following two ways −

bgcolor attribute − You can set background color for whole table or just for one cell.

background attribute − You can set background image for whole table or just for one cell.

You can also set border color also using bordercolor attribute.

Note − The bgcolor , background , and bordercolor attributes deprecated in HTML5. Do not use these attributes.

Here is an example of using background attribute. Here we will use an image available in /images directory.

This will produce the following result. Here background image did not apply to table's header.

Table Height and Width

You can set a table width and height using width and height attributes. You can specify table width or height in terms of pixels or in terms of percentage of available screen area.

Table Caption

The caption tag will serve as a title or explanation for the table and it shows up at the top of the table. This tag is deprecated in newer version of HTML/XHTML.

Table Header, Body, and Footer

Tables can be divided into three portions − a header, a body, and a foot. The head and foot are rather similar to headers and footers in a word-processed document that remain the same for every page, while the body is the main content holder of the table.

The three elements for separating the head, body, and foot of a table are −

<thead> − to create a separate table header.

<tbody> − to indicate the main body of the table.

<tfoot> − to create a separate table footer.

A table may contain several <tbody> elements to indicate different pages or groups of data. But it is notable that <thead> and <tfoot> tags should appear before <tbody>

Nested Tables

You can use one table inside another table. Not only tables you can use almost all the tags inside table data tag <td>.

Following is the example of using another table and other tags inside a table cell.

HTML Tutorial

Html graphics, html examples, html references, html table styling.

Use CSS to make your tables look better.

HTML Table - Zebra Stripes

If you add a background color on every other table row, you will get a nice zebra stripes effect.

To style every other table row element, use the :nth-child(even) selector like this:

Note: If you use (odd) instead of (even) , the styling will occur on row 1,3,5 etc. instead of 2,4,6 etc.

HTML Table - Vertical Zebra Stripes

To make vertical zebra stripes, style every other column , instead of every other row .

Set the :nth-child(even) for table data elements like this:

Note: Put the :nth-child() selector on both th and td elements if you want to have the styling on both headers and regular table cells.

Advertisement

Combine Vertical and Horizontal Zebra Stripes

You can combine the styling from the two examples above and you will have stripes on every other row and every other column.

If you use a transparent color you will get an overlapping effect.

Use an rgba() color to specify the transparency of the color:

Horizontal Dividers

If you specify borders only at the bottom of each table row, you will have a table with horizontal dividers.

Add the border-bottom property to all tr elements to get horizontal dividers:

Hoverable Table

Use the :hover selector on tr to highlight table rows on mouse over:

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. Learn HTML table and It's Attributes tutorials and training step by

    html table task

  2. Create Tables in HTML

    html table task

  3. HTML Tables

    html table task

  4. HTML And CSS Tables That You Can Use On Your Website

    html table task

  5. HTML Tables

    html table task

  6. Nested Table in HTML

    html table task

VIDEO

  1. 04 HTML Table & CSS

  2. Responsive Table Design Only HTML & CSS || How To Create Responsive Table Using HTML & CSS || Part-2

  3. Table Task

  4. 16

  5. Make HTML Table for practise!

  6. WEB

COMMENTS

  1. HTML tables

    A very common task in HTML is structuring tabular data, and it has a number of elements and attributes for just this purpose.

  2. HTML Tables

    HTML Tables - W3Schools HTML Tables is a tutorial that teaches you how to create and format tables in HTML. You will learn how to use table elements, attributes, and styles to display data in a structured and attractive way. You will also see how to use the HTML table tag from the related webpage to customize your tables.

  3. 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.

  4. HTML Tables

    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. Table of Content Basic Example of HTML Table Tags used in HTML Tables Defining Tables in HTML

  5. HTML Tables

    Learn how to use tables in HTML and how to style them with CSS. This article covers the basic tags, attributes, and features of tables, such as headings, captions, scope, cell spanning, and more. See examples of how to create and design tables with HTML tables tutorial with example code.

  6. Create An HTML Table Quickly & Easily With Our Code Example

    So, what is the proper use of HTML tables? To display tabular data. Some data sets are just easiest to understand and digest when presented in a table. If you have a data set like this to add to a website, an HTML table is the right tool for the job.

  7. 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.

  8. HTML Table (With Examples)

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

  9. Tables in HTML documents

    The HTML table model allows authors to arrange data -- text, preformatted text, images, links, forms, form fields, other tables, etc. -- into rows and columns of cells. Each table may have an associated caption (see the element) that provides a short description of the table's purpose. A longer description may also be provided (via the ...

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

    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.

  11. HTML Tables

    The HTML tables allow displaying the data (e.g. image, text, link) in columns and rows of cells. Table rows can be grouped into a head, foot, and body sections through the <thead>, <tfoot> and <tbody> elements, respectively. In HTML5, we can place <tfoot> either before or after <tbody> tag.

  12. HTML table tag

    <tr> <th> Month </th> <th> Savings </th> </tr> <tr> <td> January </td> <td> $100 </td> </tr> </table> Try it Yourself » More "Try it Yourself" examples below. Definition and Usage The <table> tag defines an HTML table. An HTML table consists of one <table> element and one or more <tr>, <th>, and <td> elements.

  13. HTML Tables

    If you want to test your skills on HTML Tables, try some of our practice exercises. Learn and improve your skills with the help of the materials provided by W3Docs. | Exercise 3

  14. HTML Tables

    The transition of web page layouts from HTML tables to CSS layout techniques underlines the importance of using the right tool for the right task. While HTML tables excel in presenting tabular data, CSS is the go-to tool for creating web page layouts.

  15. : 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.

  16. Using Tables in HTML with Exercises

    Although the table at this state doesn't look the best with this view. We shall be using CSS later to style our HTML elements to look better. Alright there we go! This is just a normal table without styling. HTML Table Exercise. Organizing Student data using HTML table. Please ensure you read the codes and comments carefully.

  17. Styling tables

    The first thing we need to do is sort out the spacing/layout — default table styling is so cramped! To do this, add the following CSS to your style.css file: A table-layout value of fixed is generally a good idea to set on your table, as it makes the table behave a bit more predictably by default.

  18. HTML Exercises

    HTML Exercises HTML Exercises Previous Next You can test your HTML skills with W3Schools' Exercises. 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

  19. HTML

    Tables Backgrounds. You can set table background using one of the following two ways −. bgcolor attribute − You can set background color for whole table or just for one cell.. background attribute − You can set background image for whole table or just for one cell.. You can also set border color also using bordercolor attribute.. Note − The bgcolor, background, and bordercolor ...

  20. HTML Table Styling

    HTML Table - Zebra Stripes. If you add a background color on every other table row, you will get a nice zebra stripes effect. To style every other table row element, use the :nth-child (even) selector like this: Note: If you use (odd) instead of (even), the styling will occur on row 1,3,5 etc. instead of 2,4,6 etc.