In HTML, you can create tables to organize and display tabular data using the <table>
, <tr>
, <th>
, and <td>
elements. Here’s how you can create a basic table:
<!DOCTYPE html>
<html>
<head>
<title>Tables in HTML</title>
</head>
<body>
<h1>Sample Table</h1>
<table border=”1″>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<td>Apples</td>
<td>$2.00</td>
<td>5</td>
</tr>
<tr>
<td>Oranges</td>
<td>$1.50</td>
<td>3</td>
</tr>
<tr>
<td>Bananas</td>
<td>$0.75</td>
<td>7</td>
</tr>
</table>
</body>
</html>
Explanation:
- The
<table>
element is used to create a table. - The
<tr>
element represents a table row. - The
<th>
element represents a table header cell. It is used to define column headings. - The
<td>
element represents a table data cell. It is used to define regular cells with data.
In the example above, we create a table with three columns: Product, Price, and Quantity. Each row in the table represents a different product along with its corresponding price and quantity.
The border
attribute on the <table>
element is used to specify the border width around the table cells. Setting it to “1” will create a simple table border.
You can customize the table’s appearance, such as adding styling, colors, and spacing, by using CSS (Cascading Style Sheets). CSS allows you to control the table layout and make it visually appealing.
Additionally, you can use attributes like colspan
and rowspan
to merge cells horizontally or vertically, respectively. This can be useful for creating more complex table layouts.
Here’s an example of a table with merged cells:
<!DOCTYPE html>
<html>
<head>
<title>Tables in HTML – Merged Cells</title>
</head>
<body>
<h1>Sample Table with Merged Cells</h1>
<table border=”1″>
<tr>
<th>Product</th>
<th colspan=”2″>Price</th>
</tr>
<tr>
<td rowspan=”2″>Apples</td>
<td>$2.00</td>
</tr>
<tr>
<td>Discounted</td>
</tr>
</table>
</body>
</html>
In this example, the first row contains the “Product” heading, and the “Price” heading spans two columns using colspan="2"
. The “Apples” cell in the second row spans two rows using rowspan="2"
, and the “Discounted” cell occupies the merged space in the second row.