HTML Tables: Table Tutorial with CSS Example Code

Estimated read time 3 min read

Introduction to HTML Tables

HTML tables are a powerful and widely used feature for displaying tabular data on web pages. They allow you to organize and present data in a structured manner, making it easier for users to understand and navigate through the information. In this tutorial, we will explore the basics of HTML tables, including how to create tables, customize their appearance using CSS, and add additional elements such as headers and footers.

Creating a Basic HTML Table

Let’s start by creating a basic HTML table structure. Here’s an example of a simple table with three columns and three rows:

<table>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
    <th>Header 3</th>
  </tr>
  <tr>
    <td>Data 1</td>
    <td>Data 2</td>
    <td>Data 3</td>
  </tr>
  <tr>
    <td>Data 4</td>
    <td>Data 5</td>
    <td>Data 6</td>
  </tr>
</table>

In this example, the <table> element represents the entire table. The <tr> elements define rows, and the <th> and <td> elements represent table headers and data cells, respectively. By default, table headers are displayed in bold, while table data is displayed normally.

Adding Styling with CSS

You can enhance the visual appearance of your HTML table using CSS. CSS allows you to customize various aspects of the table, such as colors, borders, alignment, and spacing. Here’s an example of how to apply CSS styles to our table:

<style>
  table {
    border-collapse: collapse;
    width: 100%;
  }

  th, td {
    border: 1px solid black;
    padding: 8px;
    text-align: center;
  }

  th {
    background-color: #f2f2f2;
  }

  tr:nth-child(even) {
    background-color: #f9f9f9;
  }
</style>

In this example, we define CSS styles within the <style> tags. We set the border-collapse property to collapse to remove the spacing between table cells. The border property sets the border width and style for both headers and data cells. The padding property adds spacing inside the cells, and the text-align property centers the content. We also set a background color for the table headers and alternate row colors using the nth-child selector.

Spanning Columns and Rows

Sometimes, you may need to merge adjacent cells to create a more complex layout. HTML provides the colspan and rowspan attributes to achieve this. Here’s an example:

Angelika Card

Hi all, my name is Angelika and I am one of the authors of the EasyTechh website. Like the rest of our team I am incredibly ambitious and I love helping people.
That's why I write here and not only here ;-) I write interesting and useful for people articles in the IT sphere and a little bit about life.
Enjoy reading.

You May Also Like

More From Author

+ There are no comments

Add yours