MakeW3web

Table Styling

Table styling is the process of applying design and aesthetics to an HTML table using CSS (Cascading Style Sheets). CSS allows you to control various aspects of a table, such as colors, borders, padding, and more. Here are some common concepts and examples of table styling.

  1. Border and border-collapse: Apply a border to the table and set the `border-collapse` property to `collapse` to ensure that adjacent borders merge into a single border.

Example:

table {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid #ccc;
}
  1. Padding and text alignment: Adjust the padding inside table cells and set the text alignment.

Example:

th, td {
  padding: 8px;
  text-align: left;
}
  1. Column headers: Style the table headers by applying background colors, font weights, or other properties to the `<th>` elements.

Example:

th {
  background-color: #f2f2f2;
  font-weight: bold;
}
  1. Zebra-striping: Apply alternating background colors to table rows for better readability. Use the `:nth-child` pseudo-class to achieve this effect.

Example:

tr:nth-child(even) {
  background-color: #f2f2f2;
}
  1. Hover effect: Add a hover effect to table rows to highlight the row when the user hovers over it.

Example:

tr:hover {
  background-color: #ddd;
}

Here's a complete example of an HTML table with various styling concepts applied:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Table Styling Example</title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
            border: 1px solid #ccc;
        }
        th, td {
            padding: 8px;
            text-align: left;
            border: 1px solid #ccc;
        }
        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
        tr:hover {
            background-color: #ddd;
        }
    </style>
</head>
<body>
    <h1>Table Styling</h1>
    
    <table>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>City</th>
        </tr>
        <tr>
            <td>Alice</td>
            <td>30</td>
            <td>New York</td>
        </tr>
        <tr>
            <td>Bob</td>
            <td>25</td>
            <td>San Francisco</td>
        </tr>
        <tr>
            <td>Carol</td>
            <td>28</td>
            <td>Los Angeles</td>
        </tr>
    </table>
</body>
</html>

This example demonstrates the use of table borders, padding, text alignment, column headers, zebra-striping, and hover effects. You can customize these styles further or add additional styling properties to match your design requirements.

Was this page helpful?