The <table> element is one of the fundamental elements in HTML used to create tables of data. In this guide, we’ll cover everything you need to know about creating and styling tables with CSS.

1. Basic table structure

A basic table consists of a <table> element containing one or more <tr> (table row) elements, each of which contains one or more <td> (table cell) elements.

html
<table>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>

In this code, we’ve created a table with two rows and two columns.

2. Table headers

You can add a header row to your table using the <thead> element and header cells using the <th> element. By default, header cells are bold and centered.

html
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</tbody>
</table>

In this code, we’ve added a header row using the <thead> element and header cells using the <th> element. We’ve also added a <tbody> element to contain the data rows.

3. Styling tables with CSS

To style a table with CSS, you can use a variety of CSS properties. Here are some examples:

Table borders

You can add borders to your table using the border or border-collapse properties. The border property sets the border width and style, while the border-collapse property sets whether adjacent table cells share borders or not.

css
table {
border: 1px solid black;
border-collapse: collapse;
}

In this code, we’re setting the border of the table to a 1px solid black line and collapsing the borders so that adjacent cells share borders.

Table width

You can set the width of your table using the width property.

css
table {
width: 100%;
}

In this code, we’re setting the width of the table to 100% of its containing element.

Table cell padding and spacing

You can set the padding and spacing of your table cells using the padding and border-spacing properties, respectively.

css
table {
border-spacing: 5px;
}

td {
padding: 10px;
}

In this code, we’re setting the spacing between table cells to 5px and the padding of table cells to 10px.

Table cell background and text color

You can set the background and text color of your table cells using the background-color and color properties.

css
td {
background-color: #eee;
color: #333;
}

In this code, we’re setting the background color of table cells to light gray and the text color to dark gray.

4. Responsive tables

Tables can be challenging to make responsive on smaller screens. One approach