CSS Tables

CSS tables refer to the way CSS (Cascading Style Sheets) is used to style HTML tables. HTML tables are used to display tabular data, and CSS can be applied to control their layout, appearance, and responsiveness. CSS allows for detailed customization of table elements, including borders, padding, text alignment, colors, and more.

Basic HTML Table Structure

HTML tables are created using the <table>, <tr>, <th>, and <td> elements. Here is a simple example of an HTML table:


<table>
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
        </tr>
    </thead>
    <tbody>
        <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>
    </tbody>
</table>

Basic CSS Table Properties

CSS can be applied to tables using a variety of properties to enhance their appearance and usability.

Table Borders

You can add borders to tables, table rows, table headers, and table cells:


table {
    border-collapse: collapse; /* Merge adjacent borders into a single border */
    width: 100%; /* Make the table take up 100% of the container width */
}

th, td {
    border: 1px solid black; /* Add a 1px solid black border to headers and cells */
    padding: 8px; /* Add padding inside headers and cells */
    text-align: left; /* Left-align text in headers and cells */
}

Table Header and Row Background Colors

You can style the table headers and rows with background colors for better readability:


th {
    background-color: #f2f2f2; /* Light grey background for headers */
}

tr:nth-child(even) {
    background-color: #f9f9f9; /* Light grey background for even rows */
}

tr:hover {
    background-color: #d1e7dd; /* Light green background on hover */
}

Text Alignment and Padding

You can control the alignment of text and the padding inside the cells:


th, td {
    text-align: center; /* Center-align text in headers and cells */
    padding: 10px; /* Add padding inside headers and cells */
}