MATERI HTML #7 - TAG TABEL

2 min read 1 month ago
Published on Sep 05, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will explore how to use the table tag in HTML. Tables are essential for organizing data on web pages, making them easier for users to read and understand. By the end of this guide, you'll be able to create and style basic tables in HTML.

Step 1: Understand the Structure of an HTML Table

To create a table in HTML, you need to know the basic structure:

  • <table>: This tag defines the table.
  • <tr>: This tag defines a table row.
  • <th>: This tag defines a table header cell.
  • <td>: This tag defines a table data cell.

Example Code

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

<table>
    <tr>
        <th>Header 1</th>
        <th>Header 2</th>
    </tr>
    <tr>
        <td>Data 1</td>
        <td>Data 2</td>
    </tr>
</table>

Step 2: Create a Simple Table

Now, let’s create a basic table step-by-step.

  1. Start with the <table> tag.
  2. Add the table header using <tr> and <th>.
  3. Insert data rows using <tr> and <td>.

Example Code

Here’s how a simple table with three rows and two columns looks:

<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Alice</td>
        <td>30</td>
    </tr>
    <tr>
        <td>Bob</td>
        <td>25</td>
    </tr>
</table>

Step 3: Style Your Table

To improve the appearance of your table, you can use CSS. Here are some basic styling options:

  • Set the border for the table.
  • Add padding to table cells.
  • Change background colors for headers.

Example CSS

Add the following CSS to your HTML to style your table:

<style>
    table {
        border-collapse: collapse;
        width: 100%;
    }
    th, td {
        border: 1px solid black;
        padding: 8px;
        text-align: left;
    }
    th {
        background-color: #f2f2f2;
    }
</style>

Step 4: Add More Features

Once you are comfortable with basic tables, consider these enhancements:

  • Colspan: Merge cells horizontally.
  • Rowspan: Merge cells vertically.
  • Caption: Add a title to your table using the <caption> tag.

Example Code with Colspan and Caption

Here’s an example that includes a caption and a colspan:

<table>
    <caption>Student Age Data</caption>
    <tr>
        <th>Name</th>
        <th colspan="2">Age</th>
    </tr>
    <tr>
        <td>Alice</td>
        <td>30</td>
        <td>New York</td>
    </tr>
</table>

Conclusion

You’ve now learned how to create and style tables in HTML. Tables are a powerful way to present data on your website. As you continue developing your HTML skills, experiment with more complex tables and styles. Consider exploring additional resources on CSS to further enhance your web design abilities. Happy coding!