Geek Slack

Introduction to CSS
About Lesson



CSS Tables


CSS Tables

CSS provides various properties to style HTML tables, making them more attractive and readable.

1. Basic Table Styling

You can use basic CSS properties to style tables, such as border, padding, and background-color.

Example:

<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Alice</td>
        <td>30</td>
    </tr>
    <tr>
        <td>Bob</td>
        <td>25</td>
    </tr>
</table>

<style>
table {
    width: 100%;
    border-collapse: collapse;
}
th, td {
    padding: 10px;
    border: 1px solid #ddd;
}
th {
    background-color: #f2f2f2;
}
</style>

2. Zebra Striped Table

Adding alternating row colors, known as “zebra striping,” improves readability.

Example:

<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Alice</td>
        <td>30</td>
    </tr>
    <tr>
        <td>Bob</td>
        <td>25</td>
    </tr>
</table>

<style>
table {
    width: 100%;
    border-collapse: collapse;
}
th, td {
    padding: 10px;
    border: 1px solid #ddd;
}
th {
    background-color: #f2f2f2;
}
tr:nth-child(even) {
    background-color: #f9f9f9;
}
</style>

3. Hoverable Table

You can add a hover effect to rows for better interactivity.

Example:

<table>
    <tr>
        <th>Name</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Alice</td>
        <td>30</td>
    </tr>
    <tr>
        <td>Bob</td>
        <td>25</td>
    </tr>
</table>

<style>
table {
    width: 100%;
    border-collapse: collapse;
}
th, td {
    padding: 10px;
    border: 1px solid #ddd;
}
th {
    background-color: #f2f2f2;
}
tr:nth-child(even) {
    background-color: #f9f9f9;
}
tr:hover {
    background-color: #f1f1f1;
}
</style>

4. Responsive Table

Making tables responsive involves adding a container with overflow properties to allow horizontal scrolling on small screens.

Example:

<div style="overflow-x:auto;">
    <table>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Occupation</th>
        </tr>
        <tr>
            <td>Alice</td>
            <td>30</td>
            <td>Engineer</td>
        </tr>
        <tr>
            <td>Bob</td>
            <td>25</td>
            <td>Designer</td>
        </tr>
    </table>
</div>

<style>
table {
    width: 100%;
    border-collapse: collapse;
}
th, td {
    padding: 10px;
    border: 1px solid #ddd;
}
th {
    background-color: #f2f2f2;
}
tr:nth-child(even) {
    background-color: #f9f9f9;
}
tr:hover {
    background-color: #f1f1f1;
}
</style>

Conclusion

Using CSS, you can enhance the appearance and usability of HTML tables. By applying different styles, you can make tables more readable and interactive.

Join the conversation