To create a table in HTML, you use a combination of specific HTML tags, each defining a part of the table structure. The core tags are <table>
, <tr>
, <th>
, and <td>
.
Here's a breakdown of how to build a table:
-
The
<table>
Tag: This is the container for your entire table. It tells the browser that you're creating a table.<table> </table>
-
The
<tr>
Tag (Table Row): Inside the<table>
tag, you use<tr>
tags to define each row of the table.<table> <tr> </tr> <tr> </tr> </table>
-
The
<th>
Tag (Table Header): The<th>
tag is used within a<tr>
to define a header cell. These cells typically contain column titles and are often displayed in bold.<table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> </tr> </table>
-
The
<td>
Tag (Table Data): The<td>
tag is used within a<tr>
to define a standard data cell. These cells contain the actual data of the table.<table> <tr> <th>Header 1</th> <th>Header 2</th> </tr> <tr> <td>Data 1</td> <td>Data 2</td> </tr> </table>
Putting it All Together - Example:
Here's a complete example of a simple HTML table:
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Example</title>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Occupation</th>
</tr>
<tr>
<td>Alice</td>
<td>30</td>
<td>Engineer</td>
</tr>
<tr>
<td>Bob</td>
<td>25</td>
<td>Teacher</td>
</tr>
</table>
</body>
</html>
This code will render a table with three columns (Name, Age, Occupation) and two rows of data.
Table Attributes (Optional):
You can also use attributes within the <table>
tag to control the table's appearance and behavior. Some common attributes include:
border
: Specifies the width of the table border. (e.g.,<table border="1">
) - Note: Using CSS for styling is generally preferred over HTML attributes.style
: To define CSS properties, like width, height, background color, text alignment, etc. (e.g.,<table style="width:100%">
)colspan
: Makes a cell span across multiple columns. Applied to<th>
or<td>
.rowspan
: Makes a cell span across multiple rows. Applied to<th>
or<td>
.
Styling with CSS:
While you can use attributes for basic styling, it's generally recommended to use CSS for more control over the table's appearance. You can apply CSS styles to the <table>
, <tr>
, <th>
, and <td>
elements.
For example:
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse; /* Optional: Collapses borders for a cleaner look */
}
th, td {
padding: 8px;
text-align: left;
}
</style>
This CSS code adds a solid black border to the table and its cells, collapses the borders, and adds padding to the cells for better readability.
In summary, creating tables in HTML involves using the <table>
, <tr>
, <th>
, and <td>
tags. Use CSS for styling to create visually appealing and well-structured tables.