Table Styling

Beyond borders and spacing, you can apply various CSS properties to style your tables. Alter background colors, fonts, text alignment, or even add hover effects. Well-styled tables improve readability and match the website's look and feel.

Key Topics

Background Colors

Example: Applying a background color to header cells and alternating row colors for improved readability.

<style>
th {
    background:#f0f0f0;
}
tr:nth-child(even) {
    background:#e9e9e9;
}
</style>

Hover Effects

Example: Highlighting a row when the user hovers over it.

<style>
tr:hover {
    background:#d0f0d0;
}
</style>

Styling Example

This example shows a fully styled table with alternating row colors and a hover effect. A full code sample is provided below.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" >
    <meta name="viewport" content="width=device-width, initial-scale=1.0" >
    <title>Styled Table</title>
    <style>
        table {
            border-collapse: collapse;
            width:60%;
            margin:0 auto;
        }
        th, td {
            border:1px solid #ccc;
            padding:10px;
            text-align:left;
        }
        th {
            background:#f0f0f0;
        }
        tr:nth-child(even) {
            background:#f9f9f9;
        }
        tr:hover {
            background:#d0f0d0;
        }
    </style>
</head>
<body>
    <h1>Styled Data Table</h1>
    <table>
        <tr>
            <th>Item</th>
            <th>Price</th>
        </tr>
        <tr>
            <td>Notebook</td>
            <td>$5</td>
        </tr>
        <tr>
            <td>Marker</td>
            <td>$1</td>
        </tr>
        <tr>
            <td>Stapler</td>
            <td>$3</td>
        </tr>
    </table>
</body>
</html>

Explanation: The styled table uses various CSS selectors to enhance readability: a distinct header background, alternating row colors, and a highlight on hover. This helps users parse and interact with the data more effectively.

Key Takeaways

  • Use CSS to style table backgrounds, fonts, and borders for better aesthetics.
  • Alternating row colors (striping) improves readability.
  • Hover effects guide user attention during interaction.
  • Match table styling to your site's visual design for consistency.
  • Well-styled tables enhance user experience and data comprehension.