CSS Tables

CSS Tables are a fundamental component of web design, allowing you to present data in a structured and visually appealing manner. This guide explores the intricacies of styling tables with CSS, offering detailed explanations, numerous code examples with outputs, and best practices to ensure your tables are both functional and aesthetically pleasing.

1. Introduction to CSS Tables

Tables are used to display tabular data in an organized manner. While HTML provides the basic structure of tables using elements like <table>, <tr>, <th>, and <td>, CSS enhances their appearance and functionality. Understanding how to style tables with CSS is essential for creating professional and user-friendly web pages.


<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Occupation</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>John Doe</td>
            <td>28</td>
            <td>Engineer</td>
        </tr>
        <tr>
            <td>Jane Smith</td>
            <td>34</td>
            <td>Designer</td>
        </tr>
    </tbody>
</table>
        
Name Age Occupation
John Doe 28 Engineer
Jane Smith 34 Designer

Explanation: This basic HTML table structure consists of a header section (<thead>) with column titles and a body section (<tbody>) containing data rows. CSS can be applied to enhance the table's appearance.

Back to Table of Contents

2. Basic Table Styling

Applying basic CSS styling can significantly improve the readability and visual appeal of your tables. Common properties include setting the width, text alignment, and background colors.


/* Basic Table Styling */
table {
    width: 100%;
    border-collapse: collapse;
}

th, td {
    padding: 12px;
    text-align: left;
}

th {
    background-color: #4CAF50;
    color: white;
}

tbody tr:nth-child(even) {
    background-color: #f2f2f2;
}
        

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Occupation</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>John Doe</td>
            <td>28</td>
            <td>Engineer</td>
        </tr>
        <tr>
            <td>Jane Smith</td>
            <td>34</td>
            <td>Designer</td>
        </tr>
    </tbody>
</table>
        
Name Age Occupation
John Doe 28 Engineer
Jane Smith 34 Designer

Explanation: The CSS styles applied here set the table to occupy 100% of its container's width and collapse borders for a cleaner look. Padding within table cells enhances readability, while alternating row colors improve visual distinction between rows. The header row is styled with a distinct background color and text color to differentiate it from the data rows.

Back to Table of Contents

3. Table Borders and Spacing

Fine-tuning borders and spacing can enhance the structure and clarity of your tables. CSS provides properties to customize border styles, widths, and spacing between cells.


/* Table Borders and Spacing */
table {
    border: 2px solid #4CAF50;
}

th, td {
    border: 1px solid #ddd;
    padding: 10px;
}

th {
    border-bottom: 2px solid #4CAF50;
}
        

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Occupation</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Alice Johnson</td>
            <td>30</td>
            <td>Architect</td>
        </tr>
        <tr>
            <td>Bob Williams</td>
            <td>45</td>
            <td>Manager</td>
        </tr>
    </tbody>
</table>
        
Name Age Occupation
Alice Johnson 30 Architect
Bob Williams 45 Manager

Explanation: Here, the table is given a thicker border to make it stand out. Each cell has a light border and padding to create space between the content and the borders. The header cells have a more pronounced bottom border to separate them from the data rows, enhancing the table's readability.

Back to Table of Contents

4. Table Layouts: Fixed and Automatic

Understanding table layouts is crucial for controlling how your table adapts to different content sizes. CSS offers the table-layout property, which can be set to either auto or fixed.

table-layout: auto;: The table adjusts its column widths based on the content.
table-layout: fixed;: Column widths are determined by the table's width and the width of the first row.

a. Automatic Table Layout with table-layout: auto;


/* Automatic Table Layout */
table.auto-layout {
    table-layout: auto;
    width: 100%;
    border-collapse: collapse;
}

.auto-layout th, .auto-layout td {
    border: 1px solid #ddd;
    padding: 10px;
}
        

<table class="auto-layout">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Occupation</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Christopher Alexander</td>
            <td>50</td>
            <td>Urban Planner</td>
        </tr>
        <tr>
            <td>Elizabeth Brown</td>
            <td>29</td>
            <td>Software Developer</td>
        </tr>
    </tbody>
</table>
        
Name Age Occupation
Christopher Alexander 50 Urban Planner
Elizabeth Brown 29 Software Developer

Explanation: With table-layout: auto;, the browser calculates the column widths based on the content within each cell. This allows columns to adjust dynamically, ensuring that content is displayed without overflow or excessive whitespace.


b. Fixed Table Layout with table-layout: fixed;


/* Fixed Table Layout */
table.fixed-layout {
    table-layout: fixed;
    width: 100%;
    border-collapse: collapse;
}

.fixed-layout th, .fixed-layout td {
    border: 1px solid #ddd;
    padding: 10px;
    width: 33.33%;
    overflow: hidden;
    text-overflow: ellipsis;
        white-space: nowrap;
}
        

<table class="fixed-layout">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Occupation</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Alexander the Great</td>
            <td>32</td>
            <td>Conqueror and King</td>
        </tr>
        <tr>
            <td>Marie Curie</td>
            <td>66</td>
            <td>Physicist and Chemist</td>
        </tr>
    </tbody>
</table>
        
Name Age Occupation
Alexander the Great 32 Conqueror and King
Marie Curie 66 Physicist and Chemist

Explanation: With table-layout: fixed;, the table's layout is determined by the table's width and the widths of the columns, not by the content. This ensures consistent column widths regardless of the content size. The use of overflow: hidden;, text-overflow: ellipsis;, and white-space: nowrap; prevents content from overflowing the cell boundaries, adding ellipses (…) where necessary.

Back to Table of Contents

5. Responsive Tables

Responsive tables ensure that your data remains accessible and readable across various devices and screen sizes. Techniques include making tables scrollable, adjusting layouts with media queries, and using alternative display properties.

.table-responsive: Wraps the table to allow horizontal scrolling on smaller screens.
Media Queries: Adjust table styling based on viewport width.
Display: block;: Changes table elements to block-level for better stacking on small screens.

a. Making Tables Scrollable with .table-responsive


/* Responsive Table Wrapper */
.table-responsive {
    overflow-x: auto;
}
        

<div class="table-responsive">
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Occupation</th>
                <th>Location</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Michael Scott</td>
                <td>40</td>
                <td>Regional Manager</td>
                <td>Scranton</td>
            </tr>
            <tr>
                <td>Dwight Schrute</td>
                <td>38</td>
                <td>Assistant to the Regional Manager</td>
                <td>Scranton</td>
            </tr>
        </tbody>
    </table>
</div>
        
Name Age Occupation Location
Michael Scott 40 Regional Manager Scranton
Dwight Schrute 38 Assistant to the Regional Manager Scranton

Explanation: Wrapping the table within a <div> with the class .table-responsive allows the table to scroll horizontally on smaller screens. This prevents the table from breaking the layout or causing overflow issues on mobile devices.


b. Adjusting Table Layout with Media Queries


/* Responsive Table Styling */
@media (max-width: 600px) {
    table, thead, tbody, th, td, tr { 
        display: block; 
    }
    th {
        position: absolute;
        top: -9999px;
        left: -9999px;
    }
    tr { margin-bottom: 1rem; }
    td {
        border: none;
        position: relative;
        padding-left: 50%;
    }
    td::before {
        content: attr(data-label);
        position: absolute;
        left: 0;
        width: 45%;
        padding-left: 15px;
        font-weight: bold;
        white-space: nowrap;
    }
}
        

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Occupation</th>
            <th>Location</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td data-label="Name">Pam Beesly</td>
            <td data-label="Age">28</td>
            <td data-label="Occupation">Receptionist</td>
            <td data-label="Location">Scranton</td>
        </tr>
        <tr>
            <td data-label="Name">Jim Halpert</td>
            <td data-label="Age">29</td>
            <td data-label="Occupation">Salesman</td>
            <td data-label="Location">Scranton</td>
        </tr>
    </tbody>
</table>
        
Name Age Occupation Location
Pam Beesly 28 Receptionist Scranton
Jim Halpert 29 Salesman Scranton

Explanation: This media query transforms the table layout for screens narrower than 600px. By setting table elements to display: block;, each row becomes a block element, and table headers are visually hidden. Each table cell uses the ::before pseudo-element to display the corresponding header label, ensuring that data remains understandable even on small screens.

Back to Table of Contents

6. Styling Table Headers, Rows, and Cells

Customizing the appearance of table headers, rows, and cells enhances the overall look and improves data readability. CSS provides various properties to style these elements effectively.


/* Styling Table Headers */
table th {
    background-color: #4CAF50;
    color: white;
    text-align: center;
    font-size: 18px;
}

/* Styling Table Rows */
table tbody tr {
    transition: background-color 0.3s;
}

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

/* Styling Table Cells */
table td {
    text-align: left;
    padding: 8px;
}
        

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Occupation</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Oscar Martinez</td>
            <td>40</td>
            <td>Accountant</td>
        </tr>
        <tr>
            <td>Stanley Hudson</td>
            <td>43</td>
            <td>Salesman</td>
        </tr>
    </tbody>
</table>
        
Name Age Occupation
Oscar Martinez 40 Accountant
Stanley Hudson 43 Salesman

Explanation: This styling applies a distinct background and text color to table headers, making them stand out. Rows change background color on hover, providing interactive feedback. Table cells are aligned to the left with consistent padding, enhancing readability.

Back to Table of Contents

7. Hover Effects and Striped Rows

Enhancing tables with hover effects and striped rows improves user interaction and data readability. These visual cues help users navigate and differentiate between rows easily.


/* Striped Rows */
table.striped tbody tr:nth-child(odd) {
    background-color: #f9f9f9;
}

/* Hover Effects */
table.hover tbody tr:hover {
    background-color: #f1f1f1;
}
        

<table class="striped hover">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Occupation</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Kevin Malone</td>
            <td>35</td>
            <td>Accountant</td>
        </tr>
        <tr>
            <td>Angela Martin</td>
            <td>38</td>
            <td>Accountant</td>
        </tr>
        <tr>
            <td>Meredith Palmer</td>
            <td>36</td>
            <td>Supplier Relations</td>
        </tr>
    </tbody>
</table>
        
Name Age Occupation
Kevin Malone 35 Accountant
Angela Martin 38 Accountant
Meredith Palmer 36 Supplier Relations

Explanation: Striped rows use the :nth-child selector to apply different background colors to alternate rows, enhancing readability. The hover effect changes the background color of a row when the user hovers over it, providing interactive feedback and making it easier to track data across columns.

Back to Table of Contents

8. Advanced Table Features

Advanced CSS techniques allow for more sophisticated table designs, including merging cells, adding interactive elements, and enhancing aesthetics with additional styling.

colspan and rowspan: Merge cells horizontally and vertically.
CSS Grid: Create complex table layouts.
Interactive Elements: Add buttons or links within table cells.

a. Merging Cells with colspan and rowspan


<table>
    <thead>
        <tr>
            <th>Product</th>
            <th colspan="2">Details</th>
        </tr>
        <tr>
            <th>Price</th>
            <th>Availability</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td rowspan="2">Laptop</td>
            <td>$999</td>
            <td>In Stock</td>
        </tr>
        <tr>
            <td>$899</td>
            <td>Pre-Order</td>
        </tr>
    </tbody>
</table>
        
Product Details
Price Availability
Laptop $999 In Stock
$899 Pre-Order

Explanation: The colspan attribute allows a header cell to span multiple columns, grouping related headers together. Similarly, the rowspan attribute lets a cell span multiple rows, effectively merging cells vertically. These attributes help in organizing complex table data more coherently.


b. Creating Complex Layouts with CSS Grid


/* CSS Grid Table Layout */
.grid-table {
    display: grid;
    grid-template-columns: 1fr 2fr 1fr;
    border: 1px solid #ddd;
}

.grid-table div {
    border: 1px solid #ddd;
    padding: 10px;
}

.grid-table .header {
    background-color: #4CAF50;
    color: white;
    font-weight: bold;
}

.grid-table .row:nth-child(even) {
    background-color: #f9f9f9;
}
        

<div class="grid-table">
    <div class="header">Name</div>
    <div class="header">Age</div>
    <div class="header">Occupation</div>

    <div>Timothy Green</div>
    <div>32</div>
    <div>Developer</div>

    <div>Samantha Lee</div>
    <div>28</div>
    <div>Designer</div>
</div>
        
Name
Age
Occupation
Timothy Green
32
Developer
Samantha Lee
28
Designer

Explanation: CSS Grid allows for more flexible and complex table layouts. By defining grid columns, you can control the width of each column precisely. Styling individual grid items enhances the table's appearance, and using pseudo-selectors like :nth-child can add alternate row coloring for better readability.


c. Adding Interactive Elements within Table Cells


<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Laura Palmer</td>
            <td>27</td>
            <td><button onclick="alert('Editing Laura')">Edit</button></td>
        </tr>
        <tr>
            <td>Dale Cooper</td>
            <td>35</td>
            <td><button onclick="alert('Editing Dale')">Edit</button></td>
        </tr>
    </tbody>
</table>
        
Name Age Action
Laura Palmer 27
Dale Cooper 35

Explanation: Incorporating interactive elements like buttons within table cells allows users to perform actions directly from the table. This enhances user experience by providing immediate functionality, such as editing or deleting records.

Back to Table of Contents

9. Accessibility Considerations

Ensuring that tables are accessible to all users, including those using assistive technologies, is paramount. Proper semantic markup and ARIA attributes enhance the accessibility of your tables.

<caption>: Provides a title for the table.
scope: Defines whether a header cell is a header for a row, column, or group of rows or columns.
aria-label and aria-labelledby: Offer additional labeling for complex tables.
Keyboard Navigation: Ensure that tables can be navigated using keyboard controls.

a. Adding a Caption with <caption>


<table>
    <caption>Employee Information</caption>
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Department</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Henry Cavill</td>
            <td>35</td>
            <td>IT</td>
        </tr>
    </tbody>
</table>
        
Employee Information
Name Age Department
Henry Cavill 35 IT

Explanation: The <caption> element provides a title for the table, enhancing its accessibility by offering context to users, especially those using screen readers.


b. Defining Header Scope with scope


<table>
    <thead>
        <tr>
            <th scope="col">Name</th>
            <th scope="col">Age</th>
            <th scope="col">Department</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th scope="row">Bruce Wayne</th>
            <td>40</td>
            <td>Management</td>
        </tr>
    </tbody>
</table>
        
Name Age Department
Bruce Wayne 40 Management

Explanation: The scope attribute defines whether a header cell is a header for a row (scope="row") or a column (scope="col"). This assists screen readers in accurately associating header information with corresponding data cells.


c. Using ARIA Attributes for Complex Tables


<table>
    <thead>
        <tr>
            <th scope="col">Product</th>
            <th scope="col">Price</th>
            <th scope="col">Stock</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th scope="row" aria-label="Product: Laptop">Laptop</th>
            <td>$1200</td>
            <td>In Stock</td>
        </tr>
    </tbody>
</table>
        
Product Price Stock
Laptop $1200 In Stock

Explanation: ARIA attributes like aria-label provide additional context to assistive technologies, especially for complex tables where headers may not fully describe the data. This ensures that users relying on screen readers receive comprehensive information.

Back to Table of Contents

10. Best Practices for CSS Tables

Following best practices ensures that your tables are not only visually appealing but also functional and accessible. Here are some key guidelines:

Keep It Simple: Avoid overly complex table structures unless necessary.
Consistent Styling: Maintain consistent font sizes, colors, and spacing throughout the table.
Responsive Design: Ensure tables are accessible and readable on all devices.
Accessibility: Use semantic HTML and ARIA attributes to make tables accessible to all users.
Optimize Performance: Minimize CSS complexity to ensure fast load times.
Use Appropriate Data Types: Align data types correctly (e.g., numbers to the right, text to the left).
Provide Context: Use captions and headers to give context to the data presented.

a. Keeping Tables Simple


<table>
    <caption>Sales Data</caption>
    <thead>
        <tr>
            <th>Quarter</th>
            <th>Sales</th>
            <th>Growth</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Q1</td>
            <td>$5000</td>
            <td>10%</td>
        </tr>
        <tr>
            <td>Q2</td>
            <td>$7000</td>
            <td>20%</td>
        </tr>
    </tbody>
</table>
        
Sales Data
Quarter Sales Growth
Q1 $5000 10%
Q2 $7000 20%

Explanation: Keeping tables simple ensures that the data is easily understandable. Avoiding unnecessary complexity makes the table cleaner and more user-friendly.


b. Maintaining Consistent Styling


/* Consistent Table Styling */
table.consistent {
    width: 100%;
    border-collapse: collapse;
}

table.consistent th, table.consistent td {
    border: 1px solid #ddd;
    padding: 12px;
    text-align: left;
}

table.consistent th {
    background-color: #333;
    color: white;
}

table.consistent tbody tr:nth-child(even) {
    background-color: #f9f9f9;
}
        

<table class="consistent">
    <thead>
        <tr>
            <th>Task</th>
            <th>Status</th>
            <th>Due Date</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Design Homepage</td>
            <td>Completed</td>
            <td>2023-09-15</td>
        </tr>
        <tr>
            <td>Develop Backend</td>
            <td>In Progress</td>
            <td>2023-10-01</td>
        </tr>
    </tbody>
</table>
        
Task Status Due Date
Design Homepage Completed 2023-09-15
Develop Backend In Progress 2023-10-01

Explanation: Consistent styling across tables ensures a uniform look and feel throughout your website. Applying the same padding, border styles, and colors to all tables creates a cohesive design, enhancing user experience.

Back to Table of Contents

Previous: CSS Links | Next: CSS Display

<
>